Java - JUnit


Written by Erich Gamma (of Design Patterns fame) and Kent Beck (creator of XP methodology)

A simple framework to write and run repeatable tests

JUnit features include:


  • Test Case: defines a method to run a set of tests
  • Test Suite: a collection of related test cases
  • Test Runner: runs tests and reports results
  • Failure: An anticipated error, and is produced by a call of an assertXXX method
  •  Errors : An unanticipated failure (e.g., an exception thrown inside the tested code)



The @Test annotation identifies a method as a test method.

Before and After

It was setUp and tearDown ?

Run once for each test method in fresh instance of the test classes such as if one test modifies a class field, the second will not be affected. The tests run completely independently.

You only need to implement an after method if the before method has allocated external ressources. If the before method has allocated plain java object you can ignore after. Hoewer if you allocate many megabyte of objects you might want to clear the variables pointing to these objects so they can be garbage-collected.

BeforeClass and AfterClass

This method are executed once, before and after the start of all tests.

public static void method() 



  • Ignore a test
  • A test without error is a successful test. You can then just return
  • A failed assumption does not mean the code is broken, but that the test provides no useful information. Second parameter is an hamcrest matcher

// AssumThat
// is = equal
assumeThat(targetDatabase.getDatabaseProductName(), is(Database.DB_SQLITE));
// not Null
assumeThat(Database.connect(), is(notNull()));

Test Suite

Test suite is a composite of test. It can then contains test suite and test.



The test will fails if the method takes longer than 1000 milliseconds.



The test will succeed if the method throw the named exception.

@Test (expected = Exception.class) 	


Assert is a collection of static method for checking actual values against expected ones.

Test Runner

Make sure that the junit.jar file is on classpath

Eclipse Oepe Junit Library

Documentation / Reference

Task Runner