我已经运行了这段代码,并且在 Chrome 浏览器关闭后捕获了屏幕截图(@After) 如果我注释掉 CloseBrowser();屏幕截图被捕获,但 chrome 浏览器保持打开状态。 我希望在失败的测试中捕获屏幕截图,然后关闭浏览器。
总而言之 当前的屏幕截图是在浏览器关闭后捕获的,这只是一个空白的.png 我希望在浏览器关闭之前测试失败时捕获屏幕截图
谢谢
public class TestClass extends classHelper//has BrowserSetup(); and CloseBrowser(); {
@Rule
public ScreenshotTestRule my = new ScreenshotTestRule();
@Before
public void BeforeTest()
{
BrowserSetup();// launches chromedriver browser
}
@Test
public void ViewAssetPage()
{
//My test code here//And want to take screenshot on failure
}
@After
public void AfterTest() throws InterruptedException
{
CloseBrowser();//closes the browser after test passes or fails
}
}
class ScreenshotTestRule implements MethodRule {
public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
statement.evaluate();
} catch (Throwable t) {
captureScreenshot(frameworkMethod.getName());
throw t; // rethrow to allow the failure to be reported to JUnit
}
}
public void captureScreenshot(String fileName) {
try {
new File("target/surefire-reports/").mkdirs(); // Insure directory is there
FileOutputStream out = new FileOutputStream("target/surefire-reports/screenshot-" + fileName + ".png");
out.write(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
out.close();
} catch (Exception e) {
// No need to crash the tests if the screenshot fails
}
}
};
}
}
最佳答案
您可以实现 TestNG 监听器以在测试之前或测试之后执行代码 或者当测试失败或成功时等。
像下面一样实现它,并将您的屏幕截图放在我展示的方法中
public class Listeners implements ITestListener {
Methods…
And put the screenshot code inside the method below:
@Override
public void onTestFailure(ITestResult result) {
code for screenshot
}
}
关于java - 当我的测试失败且 chrome 浏览器关闭之前(@After)时,如何对 chrome 浏览器进行屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59876744/