2

如果我想在我的测试失败时获取屏幕截图,那么最佳做法是什么?我尝试通过以下方式执行此操作:

1)覆盖AllureRunListener:

public class SimpleScreenshotTestListener extends AllureRunListener{

@Override
public void testFailure(Failure failure) {
    if (failure.getDescription().isTest()) {
        fireTestCaseFailure(failure.getException());
    } else {
        startFakeTestCase(failure.getDescription());
        fireTestCaseFailure(failure.getException());
        finishFakeTestCase();
    }
    makeScreenshot("Failure screenshot");
}   

}

方法makeScreenshot("Failure screenshot")是 Util 类中的静态方法:

public final class Util {

 private Util() {}

 @Attachment(value = "{0}", type = "image/png")
 public static byte[] makeScreenshot(String name) {
        return ((TakesScreenshot) <Thread Local Driver>).getScreenshotAs(OutputType.BYTES);
 }
}

3) 在我的 pom 文件中,我使用创建的侦听器 SimpleScreenshotTestListener:

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.18.1</version>
        <configuration>
            <testFailureIgnore>false</testFailureIgnore>
            <argLine>
                -javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar
            </argLine>
            <properties>
                <property>
                    <name>listener</name>
                    <value>cms.fireFox.Tps.SimpleScreenshotTestListener</value>
                </property>
            </properties>
        </configuration>
        <dependencies>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
        </dependencies>
    </plugin>

我的问题是:这种方式是最好的方式还是我应该更容易做到这一点。

4

1 回答 1

1

只需使用 JUnit规则,如下所示:

public class ScreenshotOnFailureRule implements TestRule {
    public Statement apply(final Statement statement, final Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                   statement.evaluate();
                } catch (Throwable t) {
                    captureScreenshot();
                    throw t;
                }
            }

            @Attachment
            private byte[] captureScreenshot() {
                try {
                    return ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
                } catch (Exception e) {
                    // No need to crash the tests if the screenshot fails
                }
            }
        };
    }
}

只要在失败时运行captureScreenshot()方法,Allure 就会将生成的 PNG 字节流附加到测试用例。进一步阅读规则。

于 2015-07-15T09:40:53.403 回答