Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit @Before vs @Rule

Tags:

java

junit

junit4

I understand that,

  • @Before and @BeforeClass run before each test, or the entire test class, respectively
  • @Rule and @ClassRule wraps each test, or the entire test class, respectively.

Let's say I need to initialize some data before each test method,

How do I decide between using @Before and @Rule? Under what conditions is one preferred over another? The same question also goes for @BeforeClass vs.@ClassRule.

like image 811
kgf3JfUtW Avatar asked Apr 03 '17 19:04

kgf3JfUtW


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.

What does @before mean in JUnit?

In JUnit 5, the tags @BeforeEach and @BeforeAll are the equivalents of @Before and @BeforeClass in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.

What is @before and @after in JUnit?

junit Getting started with junit @Before, @AfterAn annotated method with @Before will be executed before every execution of @Test methods. Analogous an @After annotated method gets executed after every @Test method. This can be used to repeatedly set up a Test setting and clean up after every test.

Can we have two @before in JUnit?

The JUnit Team therefore recommends that developers declare at most one @BeforeEach method and at most one @AfterEach method per test class or test interface unless there are no dependencies between the @BeforeEach methods or between the @AfterEach methods.


1 Answers

In order to use @Rule, you require a class that implements TestRule(preferred) or MethodRule, as can be read here. Whereas @Before and @After require a new method to be written in every test case, @Rule does not because it is only an instantiation of already existing code.

So, if you would use @Before and @After for setUp() and tearDown() that you'll be using in many test cases, it is actually a better idea to use @Rule because of code reuse. If you have a test case that requires a unique @Before and/or @After, then these annotations are preferable.

For a bit more elaborate answer with a couple examples, take a look here. Ajit explains it very well.

like image 140
Quwin Avatar answered Sep 28 '22 03:09

Quwin