我正在努力使工作中的某些測試自動化,並希望在測試失敗時添加截屏功能。我知道這可以很容易地用TestNG以乾淨的方式完成,但是我們所有的單元/集成測試都使用jUnit,所以我必須堅持這一點。Selenium + junit - 與@Rule和@After方法衝突
我有它的邏輯/代碼幾乎就緒,它的工作,但我遇到了衝突,因爲@Rule在@After tearDown()方法後執行,屆時webDriver不再存在了所以它沒有任何東西需要截圖。
這裏是我的代碼:
@Rule
public TestRule testWatcher = new TestWatcher() {
@Override
protected void failed(Throwable e, Description description) {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String scrFilename = "Screenshot_"+ DateUtils.now().getTime()+".png";
File outputFile = new File(screenshotPath, scrFilename);
try {
LOGGER.info("Saving screenshot of failed test...");
FileUtils.copyFile(scrFile, outputFile);
} catch (IOException ioe) {
LOGGER.warn("Error taking screenshot");
}
}
};
這是拆機方法:
@After
public void tearDown() {
LOGGER.info("Quitting browser");
driver.quit();
LOGGER.info("Stopping Chrome Driver Service");
chromeDriverService.stop();
}
我得到,因爲它是現在的錯誤是這樣的:
組織。 openqa.selenium.remote.SessionNotFoundException:會話ID是 null。調用quit()後使用WebDriver?
這當然是發生了什麼事。它試圖在調用driver.quit()
和chromeDriverService.stop()
後調用代碼進行屏幕截圖。如果我評論這兩行,那麼屏幕截圖將被正確保存。
什麼是正確的方法來處理這個問題?有什麼辦法可以設置它,以便@Rule先運行然後運行@After?