JUnit 5 provides ** @ParameterizedTest ** annotations that allow you to pass values from various argument sources to test methods as arguments. In this article, I would like to show you how to easily write many test cases by using one of these argument sources, ** @EnumSource **.
If you use ** @ParameterizedTest **, you need to explicitly add junit-jupiter-params
in addition to junit-jupiter-engine
as project dependencies. Also, in this sample code, AssertJ was used to verify the test results.
pom.xml
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.13.1</version>
<scope>test</scope>
</dependency>
Here, we will test the JDK's BigInteger # gcd ()
method. This method returns the greatest common divisor of itself and the given arguments.
Let's just describe the combination of two input values and the correct answer as an enum type constant.
enum GcdTestCase {
THIS_IS_BIGGER(25, 10, 5),
OTHER_IS_BIGGER(14, 21, 7),
BOTH_ARE_EVEN(12, 8, 4),
BOTH_ARE_ODD(27, 45, 9),
BOTH_ARE_ZERO(0, 0, 0),
BOTH_ARE_ONE(1, 1, 1),
THIS_IS_ZERO(0, 3, 3),
OTHER_IS_ZERO(4, 0, 4),
THIS_IS_DIVISOR(3, 12, 3),
OTHER_IS_DIVISOR(20, 4, 4),
NO_COMMON_DIVISOR(7, 9, 1);
final BigInteger a;
final BigInteger b;
final BigInteger expected;
GcdTestCase(long a, long b, long expected) {
this.a = BigInteger.valueOf(a);
this.b = BigInteger.valueOf(b);
this.expected = BigInteger.valueOf(expected);
}
}
I created 11 test cases for the time being, but it's relatively easy to add test cases later. Just increase the enumerator.
Specify the ** @ParameterizedTest ** annotation for the test method, and at the same time specify the enum type created above using the ** @EnumSource ** annotation.
@ParameterizedTest
@EnumSource(GcdTestCase.class)
public void gcdShouldReturnGreatestCommonDivisorAsExpected(GcdTestCase test) {
BigInteger actual = test.a.gcd(test.b);
assertThat(actual).isEqualTo(test.expected);
}
If you run the test you created with mvn test
, of course, all the tests will succeed.
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running org.example.junit5.tips.BigIntegerTest
[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.156 s - in org.example.junit5.tips.BigIntegerTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0
This time, I introduced how to easily write many test cases using ** @EnumSource ** of JUnit 5. The sample code is posted on GitHub. The license is The Unlicense.
Recommended Posts