Can Selenium take a screenshot on test failure with JUnit?

后端 未结 3 819
悲哀的现实
悲哀的现实 2020-12-06 04:38

When my test case fails, especially on our build server, I want to take a picture / screenshot of the screen to help me debug what happened later on. I know how to take a s

3条回答
  •  心在旅途
    2020-12-06 05:07

    If you want to quickly add this behavior to ALL your tests in the run you can use the RunListener interface to listen for test failures.

    public class ScreenshotListener extends RunListener {
    
        private TakesScreenshot screenshotTaker;
    
        @Override
        public void testFailure(Failure failure) throws Exception {
            File file = screenshotTaker.getScreenshotAs(OutputType.File);
            // do something with your file
        }
    
    }
    

    Add the listener to your test runner like this...

    JUnitCore junit = new JUnitCore();
    junit.addListener(new ScreenshotListener((TakesScreenShots) webDriver));
    
    // then run your test...
    
    Result result = junit.run(Request.classes(FullTestSuite.class));
    

提交回复
热议问题