Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a screenshot after each step in tests with JAVA and Cucumber?

What would be the best way to capture screenshots after each step when running integration tests?

Tests are written in Java using Selenium(3.0.1) and Cucumber(1.2.4).

Code for taking a screenshot after a test is below, but I need a screenshot after each method annotated with @Given, @When, @Then.

@After
public void after(Scenario scenario){
    final byte[] screenshot = driver.getScreenshotAs(OutputType.BYTES);
    scenario.embed(screenshot, "image/png");
}

Thank you for any hints.

like image 353
tetchen9 Avatar asked Oct 27 '25 09:10

tetchen9


1 Answers

Here is the Answer to your Question:

  1. Lets assume your methods are as follows:

    @Given("^Open$")
    public void Open() throws Throwable 
    {
        //your code
    }
    
    @When("^I$")
    public void I(String uname, String pass) throws Throwable 
    {
        //your code
    }
    
    @Then("^User$")
    public void User() throws Throwable 
    {
        //your code
    }
    
  2. You can write a library to take screenshots like:

    public static void screenshot(WebDriver driver, long ms)
    {
    
    try {
        TakesScreenshot ts = (TakesScreenshot) driver;
        File source = ts.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(source, new File("./ScreenShots/"+ms+"Facebook.png"));
        System.out.println("ScreenShot Taken");
    } 
    catch (Exception e) 
    {
        System.out.println("Exception while taking ScreenShot "+e.getMessage());
    }
    
    
    }
    
  3. Now you can easily call the library after every method to take the screenshot as follows:

    @Given("^Open$")
    public void Open() throws Throwable 
    {
        //your code
        Utility.screenshot(driver, System.currentTimeMillis());
    }
    
    @When("^I$")
    public void I(String uname, String pass) throws Throwable 
    {
        //your code
        Utility.screenshot(driver, System.currentTimeMillis());
    }
    
    @Then("^User$")
    public void User() throws Throwable 
    {
        //your code
        Utility.screenshot(driver, System.currentTimeMillis());
    }
    

Let me know if this Answers your Question.

like image 165
undetected Selenium Avatar answered Oct 30 '25 00:10

undetected Selenium



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!