Here’s what I want
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
class HsbColorTest {
@ParameterizedTest
@ValueSource(floats = {0, 100, 200, 360}) // mapped to hue (0-360)
@ValueSource(floats = {0, 35, 100}) // mapped to saturation (0-100)
@ValueSource(floats = {0, 35, 100}) // mapped to brightness (0-100)
void create_withValidArgs_createsExpectedColor(float hue, float saturation, float brightness) {
HsbColor hsbColor = new HsbColor(hue, saturation, brightness);
assertEquals(hue, hsbColor.getHue());
assertEquals(saturation, hsbColor.getSaturation());
assertEquals(brightness, hsbColor.getBrightness());
}
}
Unfortunately, it’s not compilable since @ValueSource
is not @Repeatable
How can I achieve a similar effect in JUnit 5?
I can do this:
@ParameterizedTest
@CsvSource({
"0, 0, 0",
"0, 35, 35",
"0, 100, 100",
"100, 0, 0",
"100, 35, 35",
"100, 100, 100",
"200, 0, 0",
"200, 35, 35",
"200, 100, 100",
"360, 0, 0",
"360, 35, 35",
"360, 100, 100"
})
void create_withValidArgs_createsExpectedColor(float hue, float saturation, float brightness) {
HsbColor hsbColor = new HsbColor(hue, saturation, brightness);
assertEquals(hue, hsbColor.getHue());
assertEquals(saturation, hsbColor.getSaturation());
assertEquals(brightness, hsbColor.getBrightness());
}
The drawback: it’s clumsy and not very readable
I can write three separate tests, but the problem is I can’t test validation of three different param values in isolation. For example, a test that ensures that valid hue
values are accepted would in effect test that the other two values passed validation as well (otherwise, the “hue test” would fail)
Heneh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.