我需要:
测试将通过TeamCity启动。我创建一个TestWatcher对象来侦听测试结果,并且每个包含测试的JUnit类都包含此TestWatcher。我有一个侦听器,它将在整个套件完成时进行侦听,但是我必须以编程方式添加它。自从我现在使用TeamCity运行测试并生成结果以来,我相信我已经失去了这种能力。我还被要求生成一个包含TeamCity结果的PDF报告。我所需要知道的是测试何时完成,以便知道何时开始构建报告。无论如何,仅通过使用TestWatcher即可完成此任务?
下面是我的TestWatcher目前的样子。 BaseTestResult只是一个包含测试结果的类,并组织它们以便于打印出来。我也在使用Selenium,并且驱动程序变量的类型为WebDriver:
@Rule
public TestWatcher watchman = new TestWatcher() {
private BaseTestResult currentTest;
private long startTime;
private long endTime;
@Override
protected void starting(Description d) {
startTime = System.currentTimeMillis();
currentTest = new BaseTestResult(d);
currentTest.setBrowser(type);
if (d.getAnnotation(TestDescription.class) != null) {
currentTest.setDescription(d.getAnnotation(
TestDescription.class).description());
}
currentTest.setSuite(d.getTestClass().getName());
}
@Override
protected void succeeded(Description d) {
currentTest.setSucceeded(true);
}
@Override
protected void failed(Throwable e, Description d) {
currentTest.setThrowable(e);
}
@Override
protected void finished(Description d) {
endTime = System.currentTimeMillis();
currentTest.setRuntime(endTime - startTime);
String fileName = d.getMethodName() + type + ".png";
File srcFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
String filePath = "./screens/" + fileName;
try {
FileUtils.copyFile(srcFile, new File(filePath));
currentTest.setScreenshotPath(filePath);
} catch (IOException e) {
log.severe(e.toString());
}
if (currentTest.getSucceeded()) {
BaseListener.getSuiteResult().addPassed(currentTest);
} else {
BaseListener.getSuiteResult().addFailed(currentTest);
}
// Quit, the web driver
if (driver != null) {
driver.quit();
}
}
};
最佳答案
你可以这样做:
@ClassRule // the magic is done here
public static TestRule classWatchman = new TestWatcher() {
@Override
protected void starting(Description desc) {
System.out.println(desc.testCount()); // insert actual logic here
}
};
这将监视整个 class ,而不是每个测试。这意味着它可以在套件开始时为您提供套件中的测试数量。然后,每次调用
BaseListener.getSuiteResult().addPassed(currentTest);
或BaseListener.getSuiteResult().addFailed(currentTest);
时,都可以检查是否已经在套件中添加了测试数量(意味着套件已完成)。或者,甚至更好
@ClassRule
public static TestRule classWatchman = new TestWatcher() {
@Override
protected void finished(Description desc) {
System.out.println("Suite completed!"); // insert actual logic here
}
};
如果您有多个包含测试的类,则可以创建一个包含所有这些类的单个AllMyTests类!然后,可以由JUnit运行此AllMyTests类。在这种情况下,@ClassRule将表现为@SuiteRule(不存在)。
@RunWith(Suite.class)
@Suite.SuiteClasses({ First.class, Second.class, Third.class })
public class AllMyTests {
// nothing to do
}