Java - JUnit
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:
- Assertions for testing expected results
- Test fixtures for sharing common test data
- Test suites for easily organizing and running tests
- Graphical and textual test runners
Articles Related
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)
Annotations
Test
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.
@BeforeClass
public static void method()
Management
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()));
Test Suite
Test suite is a composite of test. It can then contains test suite and test.
Assertion
Timeout
The test will fails if the method takes longer than 1000 milliseconds.
@Test(timeout=1000)
Exception
The test will succeed if the method throw the named exception.
@Test (expected = Exception.class)
Assert
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