Skip to content

Instantly share code, notes, and snippets.

@thombergs
Last active October 17, 2017 18:50
Show Gist options
  • Select an option

  • Save thombergs/5ae0fe55f8ecc6c4921ad6b7c6fb9563 to your computer and use it in GitHub Desktop.

Select an option

Save thombergs/5ae0fe55f8ecc6c4921ad6b7c6fb9563 to your computer and use it in GitHub Desktop.
Assumptions and Conditional Test Execution with JUnit 4 and 5
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(AssumeConnectionCondition.class)
public @interface AssumeConnection {
String uri();
}
public class AssumeConnectionCondition implements ExecutionCondition {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
Optional<AssumeConnection> annotation = findAnnotation(context.getElement(), AssumeConnection.class);
if (annotation.isPresent()) {
String uri = annotation.get().uri();
ConnectionChecker checker = new ConnectionChecker(uri);
if (!checker.connect()) {
return ConditionEvaluationResult.disabled(String.format("Could not connect to '%s'. Skipping test!", uri));
} else {
return ConditionEvaluationResult.enabled(String.format("Successfully connected to '%s'. Continuing test!", uri));
}
}
return ConditionEvaluationResult.enabled("No AssumeConnection annotation found. Continuing test.");
}
}
public class AssumingConnection implements TestRule {
private ConnectionChecker checker;
public AssumingConnection(ConnectionChecker checker) {
this.checker = checker;
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (!checker.connect()) {
throw new AssumptionViolatedException("Skipping Test!");
} else {
base.evaluate();
}
}
};
}
}
public class ConnectionChecker {
private String uri;
public ConnectionChecker(String uri){
this.uri = uri;
}
public boolean connect() {
... // try to connect to the uri
}
}
public class ConnectionCheckingJunit4Test {
@ClassRule
public static AssumingConnection assumingConnection =
new AssumingConnection(new ConnectionChecker("http://my.integration.system"));
@Test
public void testOnlyWhenConnected() {
...
}
}
@AssumeConnection(uri = "http://my.integration.system")
public class ConnectionCheckingJunit5Test {
@Test
public void testOnlyWhenConnected() {
...
}
}
public class ConnectionCheckingTest {
private ConnectionChecker connectionChecker =
new ConnectionChecker("http://my.integration.system");
@Test
public void testOnlyWhenConnected() {
assumeTrue(connectionChecker.connect());
... // your test steps
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment