Using JUnit 4
JUnit 4 has some great features that makes unit testing way easier than before. Here are some tips for using JUnit 4:
- In JUnit 3.x the test methods must start with a “test” prefix. JUnit 4 uses @Test annotation for identifying test methods. All my new tests now have the same name as the method being tested which I find is more readable.
- JUnit 4 does not require the test class to extend TestCase class. Hence, to use assertXXX methods, you need to use the static methods available in Assert class. Java 5’s static import feature can make this usage very painless: import static org.junit.Assert.*;
- JUnit 3.x provides setup and teardown methods for creating/destroying fixtures. JUnit 4 offers @Before and @After annotations that provide same functionality (remember that methods annotated with @Before and @After will run for every test method)
- @BeforeClass and @AfterClass can only be used with static methods. These methods will run only once per class
- A test can be ignored using @Ignore annotation
- The expected attribute for @Test annotation can be used to verify exceptions thrown by a method (I remember using a Junit extension to achieve this behavior long time ago)