我有一个 junit5 测试类,其中包含几个参数化(集成)测试。大多数测试使用
MethodSource
,它可以根据外部因素产生不同数量的参数。
当我运行测试时,我仅获得整个运行中执行的测试总量,无论是在 junit IDE 集成中还是在 Surefire 报告中。但我需要的是每个方法的这些数字。 IE。而不是
Tests failed: 808, passed: 2366
我需要这样的东西:
Test_1 failed: 200, passed: 1000
Test_1 failed: 100, passed: 1000
Test_1 failed: 508, passed: 366
有没有任何工具可以开箱即用地执行此操作?我可以解析可靠的报告来提取这些信息,但我想我不想相信这是最好的解决方案。
我知道我可以进行多次测试运行,每次仅执行一种测试方法。不过,我不想这样做,因为在一次测试执行期间,与外部组件的通信被缓存,我不能失去这一好处。
一种灵活的方法是在 JUnit 5 中创建自定义测试侦听器或扩展,用于收集和记录每个测试方法的统计信息。
简单的例子:
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
public class PerMethodStatisticsExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
private int passedCount = 0;
private int failedCount = 0;
@Override
public void beforeTestExecution(ExtensionContext context) {
// Initialize statistics for each test method
passedCount = 0;
failedCount = 0;
}
@Override
public void afterTestExecution(ExtensionContext context) {
// Calculate statistics after each test method
if (context.getExecutionException().isPresent()) {
failedCount++;
} else {
passedCount++;
}
// Log per-method statistics
System.out.println("Test method: " + context.getDisplayName() +
" passed: " + passedCount + ", failed: " + failedCount);
}
}
然后您可以在测试类中注册此扩展,如下所示:
@ExtendWith(PerMethodStatisticsExtension.class)
public class YourTest {
@Test
void testMethod1() {
// Your test logic
}
@Test
void testMethod2() {
// Your test logic
}
}
如果这没有帮助,请考虑提供一些测试课程的更多信息。
祝你好运!