1
public void afterTestMethod(TestContext testContext) throws Exception {
    if (testContext.getTestException() == null) {
        return;
    }
    File screenshot = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
    String testName = testContext.getTestClass().getSimpleName();
    String methodName = testContext.getTestMethod().getName();
    Files.copy(screenshot.toPath(),
    Paths.get("C:\\Users\\user\\git\\ufe-360\\UFE-TESTS\\screenshots\test.png", testName + "_" + methodName + "_" + screenshot.getName())); 
    } 
}

I have above code in my project to take screenshots after test execution. I suspect that something is missing in my code. When I'm running each test screenshots don't save in indicated path. I don't have any errors. Each test executes correctly but without screenshot.

cse
  • 4,066
  • 2
  • 20
  • 37
goney225
  • 91
  • 1
  • 1
  • 10

2 Answers2

2
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;


        private static void takeScreenshot() throws IOException, InterruptedException {
            // TODO Auto-generated method stub

            System.setProperty("webdriver.chrome.driver", "chromedriver");              
            driver = new ChromeDriver();

            driver.get("https://www.google.com/");
            Thread.sleep(2);

            TakesScreenshot scrShot =((TakesScreenshot)driver);
            File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
            File DestFile=new File("/home/XXXX/Desktop/test.png");
            FileUtils.copyFile(SrcFile, DestFile);      

        }   

Above code will open "google.com", it will take a screenshot and store it on the desktop as i have given desktop path.

Hiten
  • 724
  • 1
  • 8
  • 23
0

At the beginning of your method you have the code that will not let the screenshot done when test has no errors/exceptions. So you say "Each test executes correctly but without screenshot." and it is quite expected. from a question:

if (testContext.getTestException() == null) {
    return;
}

from your additional comment

if (ITestResult.FAILURE == result.getStatus()) {

Your logic looks like: if the test failed, make the screenshot at the moment of failure. Try modifying your test's code to make it FAIL and you should see your screenshots in a given path. If you want to implement some different logic like "make a screenshot at every test step" please correct a question as it will have some different solution.

If you just remove the if logic your code will make a screenshot after the last step of your test. (but i'm not sure such screenshot is very useful, as usually screenshots are used to help to analyze "what went wrong" and your logic perfectly covers it)

Vladimir Efimov
  • 797
  • 5
  • 13