Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit @Rule and @ClassRule

Tags:

java

junit

rule

I am writing JUnit4 test in which I am using TemporaryFolder rule. It seems that it works fine with both @Rule and @ClassRule. What is the difference between Junit @Rule and @ClassRule? Why should I use one and not another?

like image 840
Viktar Kava Avatar asked Dec 13 '16 13:12

Viktar Kava


People also ask

What is @ClassRule in JUnit?

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 @rule in JUnit?

Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed. For example, Using @Timeout rule we can set the timeout for all the tests.

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 happens when a public void method is annotated with @after annotation?

Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception. The @After methods declared in superclasses will be run after those of the current class.


1 Answers

The distinction becomes clear when you have more than one test method in a class.

A @ClassRule has its before() method run before any of the test methods. Then all the test methods are run, and finally the rule's after() method. So if you have five test methods in a class, before() and after() will still only get run once each.

@ClassRule applies to a static method, and so has all the limitations inherent in that.

A @Rule causes tests to be run via the rule's apply() method, which can do things before and after the target method is run. If you have five test methods, the rule's apply() is called five times, as a wrapper around each method.

Use @ClassRule to set up something that can be reused by all the test methods, if you can achieve that in a static method.

Use @Rule to set up something that needs to be created a new, or reset, for each test method.

like image 153
slim Avatar answered Sep 19 '22 06:09

slim