1.3.3 More on JUnit
Course subject(s)
Module 1. Automated Software Testing
Let’s look at some more JUnit 5 functionalities that we can use to make our life easier when writing tests!
To practice, we will write some tests for the Roman numeral problem that we have seen before. Let’s start with some basic tests and see which functionalities we can use.
Follow the steps below:
- Open your project in IntelliJ.
- Inspect the RomanNumeral class that is in the tudelft.roman package. This is the production code we want to test.
- Now, go to the RomanNumeralTest class. This class is also on the same package, but now on the test source folder.
- You should see 4 tests there. Take some time to read and understand the source code.
- Notice in each test, we have the same first line:
RomanNumeral roman = new RomanNumeral();
- We can avoid this repetition. We can use the @BeforeEach annotation. Methods with that annotation are executed before each individual test. So if we have the following @BeforeEach method:
@BeforeEach public void initialize() { System.out.print("This method is called before each test!\n"); }
And we run all the tests, we get:
Notice that the printout is repeated 4 times, once for each test! - Now, let’s just move the repeated declaration to the @BeforeEach method. Also notice how we make the roman variable to be a field of the class, so that all methods can see it:
public class RomanNumeralTestWithBeforeEach { private RomanNumeral roman; @BeforeEach public void initialize() { this.roman = new RomanNumeral(); } @Test public void singleNumber() { int result = roman.convert("I"); Assertions.assertEquals(1, result); } @Test public void numberWithManyDigits() { int result = roman.convert("VIII"); Assertions.assertEquals(8, result); } @Test public void numberWithSubtractiveNotation() { int result = roman.convert("IV"); Assertions.assertEquals(4, result); } @Test public void numberWithAndWithoutSubtractiveNotation() { int result = roman.convert("XLIV"); Assertions.assertEquals(44, result); } }
- JUnit is a powerful tool. Keep exploring it! A very good source is its manual: https://junit.org/junit5/docs/current/user-guide/
Automated Software Testing: Practical Skills for Java Developers by TU Delft OpenCourseWare is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Based on a work at https://online-learning.tudelft.nl/courses/automated-software-testing-practical-skills-for-java-developers/.