Introduction
In this post, I am going to show you how you can run methods before and after a test method runs. Junit offers 4 different annotations you can use to decide when a method runs during the lifecycle of a test. One annotation lets you run a method before all the other tests are started while another runs every time before a test is started. The annotations differ between JUnit 5 and 4, I will show how both of them work starting with JUnit 5.
JUnit 5 Lifecycle Annotations
With these lifecycle methods, you can perform the setup needed for a single test method or all the test methods inside a single class. Methods annotated with these annotations run at different times inside the entire lifecycle of a test. With JUnit 5 you can use the following lifecycle methods:
- @BeforeEach Runs before each @Test annotated method
- @AfterEach Runs after each @Test annotated method
- @BeforeAll Run only once before any test is executed in that class
- @AfterAll Run only once after any test is executed in that class
In the following example, I show you how the annotations are used. I placed a print line in each of the methods to show you what the order is when the test is executed.
|
|
Running the example results in the following output. You can see that two methods are run before and after the test.
|
|
If you want to know more about these annotations in JUnit 5 please look at the official documentation.
JUnit 4 Lifecycle annotations
With JUnit 4 you can have the same lifecycle methods as with JUnit 5 but the annotations are different if you are using JUnit 4. I would recommend you upgrade JUnit to the latest version, but if that is not possible for any reason the following example shows how to do the same thing with JUnit 4.
The lifecycle methods with 4 are:
- @Before
- @After
- @BeforeClass
- @AfterClass
They work the same as their JUnit 5 counterpart. The following example shows how you can use the Junit 4 annotations inside your test class.
|
|
The following block shows you what the output is after running the previous test class. As you can see it looks the same as with JUnit 5.
|
|
The documentation for JUnit 4 can be found here.
Conclusion
In this post, we looked at how to use the lifecycle methods of Junit 4 and 5. The annotations themselves differ between these versions, but they will work the same. I still recommend you upgrade to the latest version of JUnit if that's possible.