You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Karate UI Automation Framework中截取屏幕截图并按当前日期时间保存

Hey there! Let's break down exactly how to capture screenshots in Karate UI Automation Framework and save them with a filename based on the current date and time. It's a common requirement, and Karate makes it pretty straightforward once you know the right tricks.

Karate UI: Screenshot with Timestamped Filename

1. Understand Karate's Built-in Screenshot Method

Karate UI provides a native screenshot() method on the driver object. By default, it saves screenshots with a generic name, but we can pass a custom path/filename to override this behavior.

2. Generate a Timestamped Filename

First, we need to create a timestamp string that's safe for filenames (no special characters like colons, which are blocked on Windows). Karate has a handy karate.formatDate() utility for this:

// Generate a timestamp in yyyyMMdd_HHmmss format (e.g., 20240520_154530)
def timestamp = karate.formatDate(new java.util.Date(), 'yyyyMMdd_HHmmss')
def screenshotFileName = "screenshot_${timestamp}.png"

This format works across all operating systems and ensures each screenshot has a unique name.

3. Combine Screenshot Capture with Custom Filename

Putting it all together in a test scenario:

Feature: Capture Timestamped Screenshots
  Scenario: Take screenshot of example.com with timestamp
    Given driver 'https://example.com'
    # Wait for page to load (optional but recommended)
    And waitFor('body')
    # Generate timestamp and define save path
    And def timestamp = karate.formatDate(new java.util.Date(), 'yyyyMMdd_HHmmss')
    And def screenshotPath = "target/screenshots/screenshot_${timestamp}.png"
    # Capture and save the screenshot
    And driver.screenshot(screenshotPath)
    # Verify the save (optional)
    Then print "Successfully saved screenshot to: ${screenshotPath}"
  • Using target/screenshots/ as the directory is a good practice because build tools like Maven/Gradle automatically clean this folder when running a fresh build.
  • If you don't specify an absolute path, Karate uses your project's root directory as the base.

4. Reusable Screenshot Function (For Multiple Tests)

If you need to take screenshots in multiple scenarios, encapsulate the logic into a reusable function to avoid repetition. Create a common-utils.feature file:

Feature: Common UI Utilities
  Scenario: Define Timestamped Screenshot Function
    * def takeTimestampedScreenshot = 
      """
      function() {
        // Create screenshots directory if it doesn't exist
        var Files = Java.type('java.nio.file.Files');
        var Paths = Java.type('java.nio.file.Paths');
        var dir = Paths.get('target/screenshots');
        if (!Files.exists(dir)) {
          Files.createDirectories(dir);
        }
        // Generate timestamp and save screenshot
        var timestamp = karate.formatDate(new java.util.Date(), 'yyyyMMdd_HHmmss');
        var path = "target/screenshots/screenshot_${timestamp}.png";
        karate.driver.screenshot(path);
        karate.log("Screenshot saved to: " + path);
        return path;
      }
      """

Then call this function in any test scenario:

Feature: Test with Reusable Screenshot
  Scenario: Capture screenshot using utility function
    Given driver 'https://your-test-url.com'
    # Load the reusable function
    And call read('common-utils.feature')
    # Take screenshot
    And def screenshotPath = call takeTimestampedScreenshot
    Then print "Screenshot path: ${screenshotPath}"

5. Auto-Capture Screenshots on Test Failure

A common use case is capturing screenshots only when a test fails. You can set up an afterScenario hook in your karate-config.js to handle this automatically:

function fn() {
  karate.configure('afterScenario', function(){
    if (karate.info.failed) {
      var timestamp = karate.formatDate(new java.util.Date(), 'yyyyMMdd_HHmmss');
      var path = "target/screenshots/failure_${timestamp}.png";
      karate.driver.screenshot(path);
      karate.log("Screenshot captured for failed scenario: " + path);
    }
  });
  return {};
}

This way, you don't have to manually add screenshot logic to every scenario—Karate handles it automatically when a test fails.

Key Notes

  • Always ensure the target directory exists (the reusable function above takes care of this, but if you're writing custom code, don't skip this step).
  • Adjust the timestamp format to your preference (e.g., yyyy-MM-dd_HH-mm-ss) but avoid characters like :, /, or \ which are invalid in filenames.
  • Karate's screenshot() method supports both relative and absolute paths—use whichever fits your project structure best.

内容的提问来源于stack exchange,提问作者mohan raul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:42:46