JUnit @Before vs @Rule

kgf3JfUtW picture kgf3JfUtW · Apr 3, 2017 · Viewed 12.2k times · Source

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.

Answer

Quwin picture Quwin · Apr 4, 2017

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.