我必须编写一个分为几个步骤的测试。每个步骤都基于前一个步骤,因此如果失败,则应停止测试。
@TestMethodOrder(AlphanumericOrder.class)
public class TestCase {
@Test
public void step10() {
Assertions.assertTrue(true);
}
@Test
public void step20() {
Assertions.assertTrue(false);
}
@Test
public void step30() {
Assertions.assertTrue(true);
}
@Test
public void step40() {
Assertions.assertTrue(true);
}
}
在上面的例子中,测试应该在step20()之后终止。我实现了自定义 MethodOrder 以确保正确的执行顺序。我遇到的问题是如何在一个测试失败后停止其他测试?我尝试实现 TestWatcher 但没有成功。 JUnit5中有什么内置机制可以解决我的问题吗?
评论中分享的工作解决方案:
@ExtendWith(StepwiseExtension.class)
@TestMethodOrder(AlphanumericOrder.class)
public class TestCase {
@Test
public void step10() {
Assertions.assertTrue(true);
}
@Test
public void step20() {
Assertions.assertTrue(false);
}
@Test
public void step30() {
Assertions.assertTrue(true);
}
@Test
public void step40() {
Assertions.assertTrue(true);
}
@BeforeEach
public void before(){
}
}
class StepwiseExtension implements ExecutionCondition, TestExecutionExceptionHandler {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) {
ExtensionContext.Namespace namespace = namespaceFor(extensionContext);
ExtensionContext.Store store = storeFor(extensionContext, namespace);
String value = store.get(StepwiseExtension.class, String.class);
return value == null ? ConditionEvaluationResult.enabled("No test failures in stepwise tests") :
ConditionEvaluationResult.disabled(String.format("Stepwise test disabled due to previous failure in '%s'", value));
}
@Override
public void handleTestExecutionException(ExtensionContext extensionContext, Throwable throwable) throws Throwable {
ExtensionContext.Namespace namespace = namespaceFor(extensionContext);
ExtensionContext.Store store = storeFor(extensionContext, namespace);
store.put(StepwiseExtension.class, extensionContext.getDisplayName());
throw throwable;
}
private ExtensionContext.Namespace namespaceFor(ExtensionContext extensionContext){
return ExtensionContext.Namespace.create(StepwiseExtension.class, extensionContext.getParent());
}
private ExtensionContext.Store storeFor(ExtensionContext extensionContext, ExtensionContext.Namespace namespace){
return extensionContext.getParent().get().getStore(namespace);
}
}