一种灵活的方法是在JUnit5中创建自定义测试侦听器或扩展,以收集和记录每个测试方法的统计信息.
简单的例子:
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PerMethodStatisticsExtension implements AfterAllCallback, AfterTestExecutionCallback {
private final Map<String, Integer> passedCount = new HashMap<>();
private final Map<String, Integer> failedCount= new HashMap<>();
@Override
public void afterTestExecution(ExtensionContext context) {
final String testMethodName = context.getTestMethod().get().getName();
if (context.getExecutionException().isPresent()) {
failedCount.merge(testMethodName, 1, Integer::sum);
} else {
passedCount.merge(testMethodName, 1, Integer::sum);
}
}
@Override
public void afterAll(final ExtensionContext extensionContext) throws Exception {
log.info("Passed test statistics: " + passedCount);
log.info("Failed test statistics: " + failedCount);
}
}
然后,您可以在测试类中注册此扩展,如下所示:
@ExtendWith(PerMethodStatisticsExtension.class)
public class YourTest {
@Test
void testMethod1() {
// Your test logic
}
@Test
void testMethod2() {
// Your test logic
}
}
如果这没有帮助,请考虑提供一些测试类的更多信息.
祝好运!