引用 OP:
例如,对于失败,我想在关闭浏览器之前截屏。如果成功我只想关闭浏览器。
现在,有趣的问题是您使用哪个框架进行断言?
我假设您使用与 JBehave 捆绑在一起的 Junit,因为 JBehave 依赖于知道 JUnit 抛出的异常存在错误。
这个想法是:
a) 发生错误时抛出异常(因此需要检查每一步)
b) 截图
c) 继续测试(即关闭浏览器)
所以为了抛出异常,你真的不需要做太多事情,因为这是在使用 JUnit 的 Assert 语句时自动完成的。
例如
Assert(username.equals("expected_user").isTrue();
如果上述失败,将抛出异常。
您可以这样捕获它:
public class RunnerExtension implements AfterTestExecutionCallback {
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
Boolean testResult = context.getExecutionException().isPresent();
System.out.println(testResult); //false - SUCCESS, true - FAILED
}
}
@ExtendWith(RunnerExtension.class)
public abstract class Tests {
}
取自这个答案:
JUnit5 - How to get test result in AfterTestExecutionCallback
所以基本上你在每个断言执行之后覆盖标准行为。在上述情况下,您可以添加(抛出异常时 --> 截图)。
这是 Selenium-Java 的截图代码:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
希望以上内容有所帮助!