This entry describes how to use "@ValueSource" in "Parametrised Test" which makes it easier to write tests with different parameters when writing unit tests in JUnit5.
This is the entry for the second day of Advent Calendar 2019 to make an Enterprise calculator.
--Those who are familiar with JUnit4 but have not yet used the convenient functions of JUnit5.
JUnit5 is a test framework that is a major overhaul of JUnit4. Some features have been completely removed, while others have been added.
Among the newly added functions is "Parameterized Tests". This helps you to write a test easily by passing various values to the arguments of one test case as parameters.
According to the documentation, the "junit-jupiter-params" artifact must be available to run Parameterized Tests. This entry uses SpringBoot and uses spring-boot-starter-test for testing, but in this case spring-boot Just write one line of -starter-test and the dependency to junit-jupiter-params is also specified.
I put the following specifications in build.gradle. With SpringInitializr, he also added a specification not to use "junit-vintage-engine" which supports running tests written in JUnit3 and Junit4.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
When writing JUnit, I use "AssertJ" to check the results because I like readability. The following line is added to build.gradle.
testImplementation group: 'org.assertj', name: 'assertj-core', version: '3.14.0'
Below is an example of a source for testing with ValueSource.
@ParameterizedTest
@ValueSource(chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'})
public void push_single_success(char c) {
DeskCalculator dc = new DeskCalculator();
dc.pushChar(c);
assertThat(dc.getCurrentValue()).isEqualTo(new BigDecimal(new String(new char[]{c})));
}
The "pushChar" method of the DeskCalculator class targeted in this test has the following functions.
The test execution results are shown in the figure below. It has been tested for 10 pieces.
I tested the numbers above, but I'll also write the following test to see the second behavior.
@ParameterizedTest
@ValueSource(chars = {'+', '-', '*', '/', 'A', '!', ' '})
public void push_single_invalid_char_success(char c) {
DeskCalculator dc = new DeskCalculator();
dc.pushChar(c);
assertThat(dc.getCurrentValue()).isEqualTo(BigDecimal.ZERO);
}
As mentioned in the above two examples, by passing multiple parameters to the @ValueSource part, tests for multiple values will be executed.
In this entry, we covered the "Parametrised Test" that was added in JUnit 5. In addition to @ValueSource, ParametrisedTest also provides a function to pass multiple arguments and a function to read a value from CSV.
The code used in this entry is tagged and stored on GitHub. https://github.com/hrkt/commandline-calculator/releases/tag/0.0.3
Recommended Posts