[英]How take screenshot and attach it to Allure report, while using Cucumber and JUnit?
我在我的自動化測試項目中使用 Cucumber、Selenium、Java、Maven 和 JUnit 堆棧。
目標是對失敗和損壞的測試進行截圖。 我找到了 Java/Maven/JUnit 堆棧的解決方案:
@Rule
public TestWatcher screenshotOnFailure = new TestWatcher() {
@Override
protected void failed(Throwable e, Description description) {
makeScreenshotOnFailure();
}
@Attachment("Screenshot on failure")
public byte[] makeScreenshotOnFailure() {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}
};
但是,當然它在使用 Cucumber 的情況下不起作用,因為它不使用任何 @Test 方法。
所以,我決定將@Rule 更改為@ClassRule,讓它監聽任何失敗,所以這里是:
@ClassRule
public static TestWatcher screenshotOnFailure = new TestWatcher() {
@Override
protected void failed(Throwable e, Description description) {
makeScreenshotOnFailure();
}
@Attachment("Screenshot on failure")
public byte[] makeScreenshotOnFailure() {
logger.debug("Taking screenshot");
return ((TakesScreenshot) Application.getInstance().getWebDriver()).getScreenshotAs(OutputType.BYTES);
}
};
這個解決方案對我沒有幫助。
所以,問題是:“當我在我的測試項目中使用 Java/Selenium/Cucumber/JUnit/Maven 時,如何在失敗時附加屏幕截圖?”
解決方案是將以下代碼添加到定義類中:
@After
public void embedScreenshot(Scenario scenario) {
if (scenario.isFailed()) {
try {
byte[] screenshot = ((TakesScreenshot) Application.getInstance().getWebDriver())
.getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
} catch (Exception e) {
e.printStackTrace();
}
}
}
在GlobalGlue中
public class GlobalGlue {
@Before
public void before(Scenario scenario) throws Exception {
CONTEXT.setScenario(scenario);
}
@After
public void after() {
WebDriverUtility.after(getDriver(), CONTEXT.getScenario());
}
}
創建另一個類WebDriverUtility,然后在該add方法中:
public static void after(WebDriver driver, Scenario scenario) {
getScreenshot(driver, scenario);
driver.close();
}
和
public static void getScreenshot(WebDriver driver, Scenario scenario) {
if (scenario.isFailed()) {
final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
log.info("Thread: " + Thread.currentThread().getId() + " :: "
+ "Screenshot taken and inserted in scenario report");
}
}
主要部分是您需要在場景失敗時將屏幕截圖嵌入場景:
final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
ExecutionContext.java
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import cucumber.api.Scenario;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
/**
* Maintains one webdriver per scenario and one scenario per thread.
* Can be used for parallel execution.
* Assumes that scenarios within one feature are not parallel.
* Can be rewritten using <code>ThreadLocal</code>.
*
* @author dkhvatov
*/
public enum ExecutionContext {
CONTEXT;
private static final Logger log = LogManager.getLogger(ExecutionContext.class);
private final LoadingCache<Scenario, WebDriver> webDrivers =
CacheBuilder.newBuilder()
.build(CacheLoader.from(scenario ->
WebDriverUtility.createDriver()));
private final Map<String, Scenario> scenarios = new ConcurrentHashMap<>();
/**
* Lazily gets a webdriver for the current scenario.
*
* @return webdriver
*/
public WebDriver getDriver() {
try {
Scenario scenario = getScenario();
if (scenario == null) {
throw new IllegalStateException("Scenario is not set for context. " +
"Please verify your glue settings. Either use GlobalGlue, or set " +
"scenario manually: CONTEXT.setScenario(scenario)");
}
return webDrivers.get(scenario);
} catch (ExecutionException e) {
log.error("Unable to start webdriver", e);
throw new RuntimeException(e);
}
}
/**
* Gets scenario for a current thread.
*
* @return scenario
*/
public Scenario getScenario() {
return scenarios.get(Thread.currentThread().getName());
}
/**
* Sets current scenario. Overwrites current scenario in a map.
*
* @param scenario scenario
*/
public void setScenario(Scenario scenario) {
scenarios.put(Thread.currentThread().getName(), scenario);
}
}
這樣,您可以將屏幕附加到您的吸引力報告中。 還可以在pom文件中使用最新的誘惑版本
import com.google.common.io.Files;
import io.qameta.allure.Attachment;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
public class ScreenshotUtils {
@Attachment(type = "image/png")
public static byte[] screenshot(WebDriver driver)/* throws IOException */ {
try {
File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
return Files.toByteArray(screen);
} catch (IOException e) {
return null;
}
}
}
Pom文件:
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-cucumber4-jvm</artifactId>
<version>${allure.version}</version>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-junit4</artifactId>
<version>${allure.version}</version>
<scope>test</scope>
</dependency>
public static void TakeScreenshot(string text)
{
byte[] content = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
AllureLifecycle.Instance.AddAttachment(text, "image/png", content);
}
public static void Write(By by, string text)
{
try
{
driver.FindElement(by).SendKeys(text);
TakeScreenshot( "Write : " + text);
}
catch (Exception ex)
{
TakeScreenshot( "Write Failed : " + ex.ToString());
Assert.Fail();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.