JUnit 4 Class LifeCycle | What Runs When Annotations?
JUnit 4 – Which test methods run? When?
JUnit 4 has a simple run cycle for test classes based on annotations.
The four key annotations are
- @BeforeClass
- @AfterClass
- @Before
- @After
JUnit 4 – What Runs When Lifecycle
JUnit 4 will now execute these methods with a lifecycle that runs in this order
- setupOnlyOnce() — this method must be static
- setUp()
- testAFewLinesHere() — the first test method
- tearDown()
- setUp()
- testAFewLinesThere() — the second test method
- tearDown()
- tearDownOnlyOnce() — this method must be static
That is the order JUnit4 will run your tests. See the Java JUnit test code below.
Note that it is best to avoid the one initializers. Use it only when necessary. If you need to use it – then maybe look to see if you can refactor your code so that you do not need to use them.
It is common practise to do one-time initializers if the setup is extremely resource intensive (taking more than 1 minute).
My Unit Test is Fat
If your unit test is really fat , know that there is a thin skeletal test in there just dying to get out.
Unit tests are born to be lightweight.
JUnit (Java) Test Class Skeleton
Note that the list initializer is run before each test method – it is run twice.
public class BuildBusinessWebsitesTest {
private List