我需要:
- 观看测试
- 收集信息
- 根据测试生成报告
测试将通过 TeamCity 启动。我创建了一个 TestWatcher 对象来监听测试结果,这个 TestWatcher 包含在每个包含测试的 JUnit 类中。我有一个监听器,它会在整个套件完成时监听,但我必须以编程方式添加它。由于我现在使用 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 类!这个 AllMyTests 类然后可以由 JUnit 运行。在这种情况下,@ClassRule 将表现为 @SuiteRule(不存在)。
@RunWith(Suite.class)
@Suite.SuiteClasses({ First.class, Second.class, Third.class })
public class AllMyTests {
// nothing to do
}
关于java - 如何仅通过使用 TestWatcher 来判断 JUnit 何时完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9942825/