JUnit Updates
After talking about TDD there comes time to bring my JUnit knowledge up-to-speed with 4.x and 4.8.x versions. Also, I see version 4.8.2 has finally made its way to central Maven repo.
“JUnit Kung Fu: Getting More Out of Your Unit Tests” (audio) teaches some new JUnit tricks.
- Normally we call the class
TestSomethingand methodstestFunctionalityZ(). Well, it’s kind of .. boring, isn’t it? Let’s give some respect to names! (slide 10)public class WhenSomethingHappens { @Test public void somethingShouldBeThis(){ .. } @Test public void somethingElseShouldBeThat(){ .. } @Test public void thisShouldNeverHappen(){ .. } }By replacing
'test'with'should'we emphasize that we test behavior and not implementation. - The structure of each method should normally follow Arrange-Act-Assert structure (slide 11): prepare the environment, do what needs to be done, check results.
- Hamcrest assertions! (slide 13) Part of JUnit already.
assertThat( theBiscuit, is( myBiscuit )); assertThat( x, is( not( 4 ))); assertThat( myList, hasItem( "3" ));
- Parametrized tests (slide 27).
@RunWith ( Parameterized.class ) public class WhenSomethingHappens { private int x; private int y; public WhenSomethingHappens ( int x, int y ) { this.x = x; this.y = y; } @Parameters public static Collection<Object[]> testData() { return Array.asList( new Object[][]{{ 1, 2 }, { 3, 4 }, { 5, 6 }, .. }); } @Test public void thisShouldBeThat () { assert( this.x, is( this.y - 1 )) } }Static method marked with
@Parametersprovides “bulks of data” and test instance will be initialized for each element in theCollectionreturned. This way the test method is absolutely free from any interfering loops and iterations over various values, which can be now conveniently loaded from external resources like Excel files. - JUnit
@Rules (slide 35) – AOP-like test interceptors, providing additional functionalities like temporary test folder, test errors collector, test timeout timer, etc.public class WhenSomethingHappens { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void thisShouldBeThat() { File createdFile = folder.newFile( "1.txt" ); File createdFolder = folder.newFolder( "someFolder" ); ... } } - Parallel tests (slide 48) when you run on multiply CPUs.
- Infinitest! (slide 50) Continuous testing in Eclipse and IDEA whenever sources are saved. When some test breaks one becomes aware of that immediately and not 2 hours later.
- JUnit Goodness: parameterized tests, Hamcrest,
@Ignore. - Hamcrest: A Cross-Language Library of Matchers
- JUnit: A Little Beyond @Test, @Before, @After: parameterized tests.
- Data-driven tests With JUnit 4 and Excel: parameterized tests using Excel files.
- Junit Parameterized Tests and Hamcrest Asserts – a potent mix!: parameterized tests and Hamcrest.
- JUnit in Action, 2Ed
Tidying up XML headers Web reading – 3 simple tricks that actually work



[...] See a follow-up post “JUnit Updates”. 1 [...]