Java - JUnit

> Test - Software, Framework and Library > Java - JUnit

1 - About

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:

Advertising

3 - Terminology

  • 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)

4 - Annotations

4.1 - Test

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

4.2 - 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.

Advertising

4.3 - BeforeClass and AfterClass

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

@BeforeClass 
public static void method() 

5 - Management

5.1 - Ignore

  • Ignore a test
@Ignore
  • A test without error is a successful test. You can then just return
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
assumeNotNull()
assumeNoException()
assumeTrue()
 
// AssumThat
// is = equal
assumeThat(targetDatabase.getDatabaseProductName(), is(Database.DB_SQLITE));
// not Null
assumeThat(Database.connect(), is(notNull()));

6 - Test Suite

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

7 - Assertion

7.1 - Timeout

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

@Test(timeout=1000) 	
Advertising

7.2 - Exception

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

@Test (expected = Exception.class) 	

7.3 - Assert

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

8 - Test Runner

Make sure that the junit.jar file is on classpath

9 - Documentation / Reference