[英]Selenium webdriver for Chrome is not saving screenshots in indicated path
public void afterTestMethod(TestContext testContext) throws Exception {
if (testContext.getTestException() == null) {
return;
}
File screenshot = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
String testName = testContext.getTestClass().getSimpleName();
String methodName = testContext.getTestMethod().getName();
Files.copy(screenshot.toPath(),
Paths.get("C:\\Users\\user\\git\\ufe-360\\UFE-TESTS\\screenshots\test.png", testName + "_" + methodName + "_" + screenshot.getName()));
}
}
我的項目中有上面的代碼,可以在測試執行后截取屏幕截圖。 我懷疑我的代碼中缺少某些內容。 當我運行每個測試屏幕截圖時,請不要將其保存在指定的路徑中。 我沒有任何錯誤。 每個測試都能正確執行,但沒有屏幕截圖。
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
private static void takeScreenshot() throws IOException, InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "chromedriver");
driver = new ChromeDriver();
driver.get("https://www.google.com/");
Thread.sleep(2);
TakesScreenshot scrShot =((TakesScreenshot)driver);
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
File DestFile=new File("/home/XXXX/Desktop/test.png");
FileUtils.copyFile(SrcFile, DestFile);
}
上面的代碼將打開“ google.com”,它將截取屏幕截圖並將其存儲在桌面上,就像我給定的桌面路徑一樣。
在方法開始時,您將擁有在測試沒有錯誤/異常時不會讓屏幕截圖完成的代碼。 因此,您說“每個測試都能正確執行,但沒有屏幕截圖。” 這是完全可以預期的。 從一個問題:
if (testContext.getTestException() == null) {
return;
}
從您的附加評論
if (ITestResult.FAILURE == result.getStatus()) {
您的邏輯如下:如果測試失敗,請在失敗時制作屏幕截圖。 嘗試修改測試代碼以使其失敗,您應該在給定的路徑中看到屏幕截圖。 如果您想實現一些不同的邏輯,例如“在每個測試步驟都做一個屏幕截圖”,請更正一個問題,因為它將有一些不同的解決方案。
如果僅刪除if
邏輯,則您的代碼將在測試的最后一步之后生成屏幕截圖。 (但我不確定此類屏幕截圖是否非常有用,因為通常使用屏幕截圖來幫助分析“出了什么問題”,並且您的邏輯可以完全涵蓋其中)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.