JUnit @Before vs @Rule

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)