简体   繁体   中英

Can Selenium take a screenshot on test(Assert.assertEquals()) failure?

I am new to Selenium, and I am stuck with Selenium taking screenshots when Assert equals fails. I am using TestNG.

When testcase fails on server side, it needs to take a screenshot of a page, so that i can exactly know where it went wrong.

I wrap the code in try catch block and in catch, I am taking a screenshot.

The Screenshot feature is working when O see selenium issues such as, where the element not visible, Unable to click on an element.

But this is failing for Assert.equals(). When Assert.assertEquals() fails, I am expecting it goes to catch and takes a screenshot. Can anyone please clarify my doubts?

Below is the code snippet, how I am trying to achive this:

try {


Assert.assertEquals(expected,actualoutput,message) //it fails

}

catch {
Selenium taking screenshot  // iam not able to take screenshot
}

While the comments are true, I offer you workaround - change Assert to if :

if (!message.equals(expected)){
   takeScreenshot(outputfile.jpg);
}

You might be catching an exception, whereas Assert when it fails throws an Error.

However, I think testng provides you other hooks where you can share the logic of taking screenshots on failures across your tests.

One way to achieve this is to put the screenshot taking code in onTestFailure provided by the ITestListener interface. This way you can avoid putting all your verifications in try-catch blocks.

Recently TestNG has also added some flexibility in doing asserts . You can try exploring that as well.

I suggest use annotation @AfterMethod which call @Override Method to taking screen short if Result is failed

@AfterMethod
        public void onTestFailure(ITestResult testResult) throws IOException {
          if(testResult.getStatus() == ITestResult.FAILURE){
              System.out.println(testResult.getStatus());
            }

@Override
public void onTestFailure(ITestResult result) {
        System.out.println("***** Error " + result.getName() 
                                         + " test has failed *****");

        <Code and Logic>
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM