Posts Tagged ‘JUnit’

Using JUnit 4

June 7th, 2008 No comments

JUnit 4 has some great features that makes unit testing way easier than before. Here are some tips for using JUnit 4:

  1. 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.
  2. 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.*;
  3. 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)
  4. @BeforeClass and @AfterClass can only be used with static methods. These methods will run only once per class
  5. A test can be ignored using @Ignore annotation
  6. 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)
Categories: Solutions Log Tags: