Skip to content

Instantly share code, notes, and snippets.

@beatngu13
Created July 14, 2021 20:25
Show Gist options
  • Save beatngu13/a69127a635c8f1a1da3b5a8ba358438d to your computer and use it in GitHub Desktop.
Save beatngu13/a69127a635c8f1a1da3b5a8ba358438d to your computer and use it in GitHub Desktop.
Poor man's JUnit 5 scenario test (see https://github.com/junit-team/junit5/issues/48)
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
class AbortRemainingTestsExtension implements TestExecutionExceptionHandler, BeforeTestExecutionCallback {
private static final String STORE_KEY = "abort";
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
getStore(context).put(STORE_KEY, true);
throw throwable;
}
@Override
public void beforeTestExecution(ExtensionContext context) throws Exception {
boolean abort = getStore(context).getOrDefault(STORE_KEY, Boolean.class, false);
Assumptions.assumeFalse(abort, "A previous failure aborted this test");
}
private ExtensionContext.Store getStore(ExtensionContext context) {
return context.getRoot().getStore(ExtensionContext.Namespace.create(getClass()));
}
}
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ExtendWith(AbortRemainingTestsExtension.class)
class PoorMansScenarioTest {
@Test
@Order(1)
void foo() {
System.out.println("You should see this");
}
@Test
@Order(2)
void bar() {
throw new AssertionError();
}
@Test
@Order(3)
void baz() {
System.out.println("You should not see this");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment