Skip to content

Instantly share code, notes, and snippets.

@alexec
Last active January 20, 2023 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexec/7e065b4049a8787fa9ac3f2ca522acf3 to your computer and use it in GitHub Desktop.
Save alexec/7e065b4049a8787fa9ac3f2ca522acf3 to your computer and use it in GitHub Desktop.
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.junit.jupiter.api.extension.TestWatcher;
/** For ordered tests only, fail fast. */
public class FailFast implements InvocationInterceptor, TestWatcher {
private static final Map<Integer, Boolean> CLASS_FAILED = new HashMap<>(Map.of(0, false));
private final Map<Integer, Boolean> methodSucceeded = new HashMap<>(Map.of(0, true));
@Override
public void interceptTestMethod(
Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext)
throws Throwable {
var classOrder = extensionContext.getRequiredTestClass().getAnnotation(Order.class);
if (classOrder != null) assumeFalse(CLASS_FAILED.getOrDefault(classOrder.value() - 1, false));
var methodOrder = extensionContext.getRequiredTestMethod().getAnnotation(Order.class);
if (methodOrder != null)
assumeTrue(methodSucceeded.getOrDefault(methodOrder.value() - 1, false));
invocation.proceed();
}
@Override
public void testSuccessful(ExtensionContext context) {
var methodOrder = context.getRequiredTestMethod().getAnnotation(Order.class);
if (methodOrder != null) methodSucceeded.put(methodOrder.value(), true);
}
@Override
public void testFailed(ExtensionContext context, Throwable cause) {
var classOrder = context.getRequiredTestClass().getAnnotation(Order.class);
if (classOrder != null) CLASS_FAILED.put(classOrder.value(), true);
}
}
@alexec
Copy link
Author

alexec commented Jan 20, 2023

You must annotated test classes with @ExtendWith(FailFast.class).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment