JUnit is a simple framework to write repeatable tests for Java programming language. It is an instance of the xUnit architecture for unit testing frameworks.
Main features consist of:
Useful extension for JUnit:
Parameter | Context | Details |
---|---|---|
@BeforeClass | Static | Executed when the class is first created |
@Before | Instance | Executed before each test in the class |
@Test | Instance | Should be declared each method to test |
@After | Instance | Executed after each test in the class |
@AfterClass | Static | Executed before destruction of the class |
Example Test Class Format
public class TestFeatureA {
@BeforeClass
public static void setupClass() {}
@Before
public void setupTest() {}
@Test
public void testA() {}
@Test
public void testB() {}
@After
public void tearDownTest() {}
@AfterClass
public static void tearDownClass() {}
}
}
One benefit to using parameters is that if one set of data fails, execution will just move to the next set of data instead of stopping the whole test.
There are benefits for either. Extending ExternalResource
it's convenient, especially if we only require a before()
to set something up.
However, we should be aware that, since the before()
method is executed outside of the try...finally
, any code that is required to do clean up in after()
won't get executed if there is an error during the execution of before()
.
This is how it looks inside ExternalResource
:
before();
try {
base.evaluate();
} finally {
after();
}
Obviously, if any exception is thrown in the test itself, or by another nested rule, the after will still get executed.