How to Implement Video Recording with ScreenRecorderHelpers During Test Execution

To implement video recording with ScreenRecorderHelpers during test execution in the anhtester/automationframeworkselenium project, set VIDEO_RECORD=yes in config.properties and let the TestNG TestListener automatically manage the Monte Screen Recorder lifecycle for each test method.

The anhtester/automationframeworkselenium repository provides a built-in video capture capability that integrates directly with TestNG listeners. This implementation leverages the Monte Screen Recorder library wrapped in a custom helper class to generate individual AVI files for every test execution without requiring manual recorder management in your test scripts.

Architecture Overview

The video recording system consists of three coordinated components:

  • ScreenRecorderHelpers – Extends org.monte.screenrecorder.ScreenRecorder to handle file naming and directory creation
  • TestListener – Global TestNG listener that initializes the recorder and triggers start/stop events synchronized with test lifecycle hooks
  • FrameworkConstants – Loads the VIDEO_RECORD property from src/test/resources/config/config.properties to determine if recording should activate

The recorder only initializes when three conditions are met: the VIDEO_RECORD property equals "yes", the property is non-null, and the environment is not headless (checked via GraphicsEnvironment.isHeadless()).

Enabling Video Recording in Configuration

Create or modify src/test/resources/config/config.properties to activate the feature:


# Enable video capture

VIDEO_RECORD = yes

# Optional: Customize output directory (default is exports/ExportData/Videos)

EXPORT_VIDEO_PATH = exports/ExportData/Videos

The framework reads these constants during static initialization of FrameworkConstants. If VIDEO_RECORD is missing or set to any value other than "yes", the TestListener skips recorder initialization to conserve resources.

The ScreenRecorderHelpers Implementation

Located at src/main/java/com/anhtester/helpers/ScreenRecorderHelpers.java, this class extends the Monte Screen Recorder to provide test-specific file naming and directory management.

Constructor and Configuration

The constructor configures the recorder with AVI format, 15 FPS frame rate, and 24-bit color depth:

public ScreenRecorderHelpers() throws IOException, AWTException {
    super(GraphicsEnvironment.getLocalGraphicsEnvironment()
            .getDefaultScreenDevice().getDefaultConfiguration(),
          new Rectangle(0, 0,
            Toolkit.getDefaultToolkit().getScreenSize().width,
            Toolkit.getDefaultToolkit().getScreenSize().height),
          new Format(MediaTypeKey, FormatKeys.MediaType.FILE, MimeTypeKey, MIME_AVI),
          new Format(MediaTypeKey, FormatKeys.MediaType.VIDEO,
                     EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                     CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                     DepthKey, 24,
                     FrameRateKey, Rational.valueOf(15),
                     QualityKey, 1.0f,
                     KeyFrameIntervalKey, 15 * 60),
          null,  // audio disabled
          new File("./" + FrameworkConstants.EXPORT_VIDEO_PATH + "/"));
}

Recording Control Methods

The class exposes simplified methods for the listener to control recording:

public void startRecording(String fileName) {
    this.fileName = fileName;
    try { 
        start(); 
    } catch (IOException e) { 
        throw new RuntimeException(e); 
    }
}

public void stopRecording(boolean keepFile) {
    try { 
        stop(); 
    } catch (IOException e) { 
        throw new RuntimeException(e); 
    }
    if (!keepFile) { 
        deleteRecording(); 
    }
}

When startRecording() is called, the helper stores the test name and generates a unique file name following the pattern <test-name>_dd-MM-yyyy HH-mm-ss.avi. The overridden createMovieFile method ensures the target directory exists before writing.

TestListener Integration

The TestListener class at src/test/java/com/anhtester/listeners/TestListener.java manages the recorder lifecycle through TestNG hooks.

Initialization

In the listener constructor, the recorder instantiates only when video recording is enabled and the environment supports graphics:

public TestListener() {
    try {
        boolean enableRecord = VIDEO_RECORD != null 
            && VIDEO_RECORD.toLowerCase().trim().equals("yes");
        if (enableRecord && !GraphicsEnvironment.isHeadless()) {
            screenRecorder = new ScreenRecorderHelpers();
            LogUtils.info("Screen recorder initialized.");
        } else {
            LogUtils.info("Skip screen recorder: VIDEO_RECORD=" + VIDEO_RECORD 
                          + ", Headless=" + GraphicsEnvironment.isHeadless());
        }
    } catch (Exception e) {
        LogUtils.error("Failed to init ScreenRecorder: " + e.getMessage());
    }
}

Lifecycle Hooks

The listener starts recording when a test begins:

@Override
public void onTestStart(ITestResult iTestResult) {
    LogUtils.info("Test case: " + getTestName(iTestResult) + " is starting...");
    if (VIDEO_RECORD.toLowerCase().trim().equals("yes") && screenRecorder != null) {
        screenRecorder.startRecording(getTestName(iTestResult));
    }
}

Recording stops when the test completes, regardless of outcome:

@Override
public void onTestSuccess(ITestResult iTestResult) {
    // ... other actions ...
    if (VIDEO_RECORD.trim().toLowerCase().equals("yes") && screenRecorder != null) {
        WebUI.sleep(2);
        screenRecorder.stopRecording(true);  // true preserves the file
    }
}

The same stopRecording(true) call appears in onTestFailure and onTestSkipped, ensuring every test produces a video file when the feature is active.

Running Tests and Accessing Videos

Execute your TestNG suite normally via Maven:

mvn clean test

After execution, video files appear in the configured export directory:


exports/ExportData/Videos/
 ├─ LoginTest_12-03-2026 14-05-30.avi
 ├─ AddProductTest_12-03-2026 14-06-02.avi
 └─ ...

Each file corresponds to a single test method, making it easy to correlate failures with their visual recordings.

Conditional Video Retention

To retain videos only for failed tests, modify the stopRecording call in the listener's onTestSuccess method:

// Delete video on success, keep on failure
screenRecorder.stopRecording(iTestResult.getStatus() != ITestResult.SUCCESS);

Required Dependencies

The video capability requires the Monte Screen Recorder library declared in pom.xml:

<dependency>
    <groupId>com.github.stephenc.monte</groupId>
    <artifactId>monte-screen-recorder</artifactId>
    <version>0.7.7.0</version>
</dependency>

Without this dependency, ScreenRecorderHelpers cannot compile or function.

Summary

  • Enable recording by setting VIDEO_RECORD=yes in config.properties
  • ScreenRecorderHelpers wraps the Monte library to generate unique AVI files with timestamps
  • TestListener automatically manages recorder lifecycle through onTestStart, onTestSuccess, onTestFailure, and onTestSkipped
  • File naming follows the pattern <TestName>_<dd-MM-yyyy HH-mm-ss>.avi in the EXPORT_VIDEO_PATH directory
  • Headless environments automatically disable recording to prevent initialization errors
  • Video retention is controlled by the keepFile boolean parameter in stopRecording()

Frequently Asked Questions

How do I disable video recording for specific test methods?

The framework controls recording globally through the VIDEO_RECORD property. To disable recording for specific tests, you would need to modify the TestListener to check for a custom annotation or test group before calling startRecording(), as the current implementation treats the flag as a global on/off switch for the entire suite.

What video format does ScreenRecorderHelpers produce?

The recorder generates AVI files using the TechSmith Screen Capture codec (ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE) with 24-bit color depth, 15 frames per second, and maximum quality (1.0f). These settings are hardcoded in the ScreenRecorderHelpers constructor at src/main/java/com/anhtester/helpers/ScreenRecorderHelpers.java.

Can I record video in headless mode?

No. The TestListener explicitly checks GraphicsEnvironment.isHeadless() during initialization and skips recorder creation if running in a headless environment. This prevents AWTException errors since the Monte Screen Recorder requires a graphical display to capture the screen buffer.

How do I change the video output directory?

Modify the EXPORT_VIDEO_PATH value in src/test/resources/config/config.properties. The default path is exports/ExportData/Videos, but any relative or absolute path can be specified. The ScreenRecorderHelpers constructor automatically creates the directory structure if it does not exist.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →