I have defines two rules defined in one of the test class but the weird thing is only one of them works at a time - the one defined last.
@Rule public ExpectedException exception = ExpectedException.none();
@Rule public TemporaryFolder folder= new TemporaryFolder();
I cant figure out for the life of me how to define two or more rules and use them separately
To use the JUnit rules, we need to add the @Rule annotation in the test. @Rule: It annotates the fields. It refer to the rules or methods that returns a rule. The annotated fields must be public, non-static, and subtypes of the TestRule or MethodRule.
To write a custom rule, we need to implement the TestRule interface. As we can see, the TestRule interface contains one method called apply(Statement, Description) that we must override to return an instance of Statement. The statement represents our tests within the JUnit runtime.
Annotation Type ClassRule. @Retention(value=RUNTIME) @Target(value={FIELD,METHOD}) public @interface ClassRule. Annotates static fields that reference rules or methods that return them. A field must be public, static, and a subtype of TestRule . A method must be public static, and return a subtype of TestRule .
A JUnit 4 rule is a component that intercepts test method calls and allows us to do something before a test method is run and after a test method has been run. All JUnit 4 rule classes must implement the org. junit.
I had the same problem, and i found that in that case you can use the RuleChain, like that:
public TemporaryFolder temp;
public ExpectedException thrown;
@Rule
public TestRule chain =
RuleChain.outerRule(temp = new TemporaryFolder())
.around(thrown = ExpectedException.none());
An other example you can see here, and the RuleChain javadoc also can help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With