Description
I've recently run into the problem that I wanted to use an annotation on certain test-methods, but didn't require the explicit rule as a field.
Considering an example, let's say there's a DatabaseUnavailable
annotation and a corresponding DatabaseUnavailableRule
setting up a defect database connection in case the annotation is present.
@Rule
public DatabaseUnavailableRule databaseUnavailableRule = new DatabaseUnavailableRule();
@Test
@DatabaseUnavailable
public void databaseUnavailable_ThrowsException() {
// ...
}
// more tests not requiring @DatabaseUnavailable
The rule is completely unnecessary if the test doesn't need to reference the rule's field. We could instead let the annotation reference the rule through a class reference in the annotation. This would change our example to:
// no Rule declaration necessary
@Test
@DatabaseUnavailable
public void databaseUnavailable_ThrowsException() {
// ...
}
With the DatabaseUnavailable
annotation referencing DatabaseUnavailableRule
within a meta annotation, e.g. looking like:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@AnnotationRule(DatabaseUnavailableRule.class)
public @interface DatabaseUnavailable {
}
The only limitation I can think of is that the DatabaseUnavailableRule
would have to have a constructor with no parameters so we can instantiate it with reflection. It would only be instantiated for tests annotated with the annotation.
What do you think? I'd be happy to submit a pull-request if it sounds viable.
Could also think of this working as a class annotation for all test-methods.