Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Rules in JUnit

Tags:

java

junit4

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

like image 693
jtkSource Avatar asked Jul 27 '14 15:07

jtkSource


People also ask

What is @rule annotation in JUnit?

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.

How do you create a rule in JUnit?

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.

What is a JUnit class rule?

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 .

What is a rule in JUnit 4?

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.


1 Answers

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.

like image 165
Krisztián Törőcsik Avatar answered Oct 20 '22 17:10

Krisztián Törőcsik