Reputation: 12417
I have the code for the tests provided below.
If the isApi is true, I would like to run the testExecute, otherwise, the legacyTestExecute. Basically, I have many tests can be grouped as A and B. So, I would like to run the group A tests for the isApi is true and the group B otherwise.
I can write if/ else kind of statements to handle this but is there any generic way to code this? Thank you.
Upvotes: 0
Views: 465
Reputation: 19555
In JUnit5 there are annotations to enable/disable execution of tests depending on the value of a system property or environment variable:
@Test
@EnabledIfSystemProperty(named="legacy.test", matches="(yes|true)")
public void testLegacy() {}
@Test
@DisabledIfSystemProperty(named="legacy.test", matches="(yes|true)")
public void testApi() {}
If you need to enable/disable the test based on the configuration property, you can provide custom condition:
@Target({ METHOD, TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@ExtendWith(EnabledIfPropertyCondition.class)
public @interface EnabledIfProperty {
String named();
}
ExecutionCondition
:class EnabledIfPropertyCondition implements ExecutionCondition {
private static final ConditionEvaluationResult ENABLED_BY_DEFAULT =
ConditionEvaluationResult.enabled(
"@EnabledIfProperty is not present");
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
AnnotatedElement element = context
.getElement()
.orElseThrow(IllegalStateException::new);
return findAnnotation(element, EnabledIfProperty.class)
.map(annotation -> disableIfPropertyNotSet(annotation, element))
.orElse(ENABLED_BY_DEFAULT);
}
private ConditionEvaluationResult disableIfPropertyNotSet(
EnabledIfProperty annotation, AnnotatedElement element) {
String named = annotation.named();
boolean usingApi = isUsingApi(named);
if (usingApi)
return enabled(format(
"%s is enabled because %s property is set",
element, named));
else
return disabled(format(
"%s is disabled because %s property not set",
element, named));
}
private boolean isUsingAPI(String propertyName) {
String s = "src/test/resources/brink.properties";
Resource r = new FileSystemResource(s);
Properties props = new Properties();
try {
props.load(r.getInputStream());
return BooleanUtils.toBoolean(props.getProperty(propertyName));
} catch (IOException e) {
throw new RuntimeException("We have an error for reading the access and location tokens for Brink web-service config", e);
}
}
}
Upvotes: 1