简体   繁体   English

Selenium可以对测试(Assert.assertEquals())失败进行截图吗?

[英]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. 我是Selenium的新手,当Assert equals失败时,我会抓紧Selenium截屏。 I am using TestNG. 我正在使用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. 我将代码包装在try catch块中,并在catch中截屏。

The Screenshot feature is working when O see selenium issues such as, where the element not visible, Unable to click on an element. 当O看到硒问题(例如,元素不可见,无法单击元素)时,屏幕截图功能将起作用。

But this is failing for Assert.equals(). 但这对于Assert.equals()失败。 When Assert.assertEquals() fails, I am expecting it goes to catch and takes a screenshot. 当Assert.assertEquals()失败时,我希望它能够捕获并截屏。 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 : 虽然评论是正确的,但我为您提供了解决方法-将Assert更改为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. 但是,我认为testng还为您提供了其他帮助,您可以在其中共享在测试中针对失败进行屏幕截图的逻辑。

One way to achieve this is to put the screenshot taking code in onTestFailure provided by the ITestListener interface. 实现此目的的一种方法是将屏幕截图获取代码放入ITestListener接口提供的onTestFailure中。 This way you can avoid putting all your verifications in try-catch blocks. 这样,您可以避免将所有验证都放入try-catch块中。

Recently TestNG has also added some flexibility in doing asserts . 最近,TestNG 在执行断言时也增加了一些灵活性 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其称之为@Override方法拍摄画面总之如果Result失败

@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>
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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