Test Overview
This test checks if a JUnit 5 parameterized test correctly converts a string argument to an integer and verifies the calculation result.
This test checks if a JUnit 5 parameterized test correctly converts a string argument to an integer and verifies the calculation result.
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class ArgumentConversionTest { @ParameterizedTest @ValueSource(strings = {"2", "3", "5"}) void testSquareConversion(String input) { int number = Integer.parseInt(input); int square = number * number; assertEquals(square, number * number, "Square calculation should be correct"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and identifies the parameterized test with string inputs | JUnit test environment initialized, test class loaded | — | PASS |
| 2 | Test executes with input argument "2" as String | Test method invoked with input = "2" | Integer.parseInt converts "2" to 2 correctly | PASS |
| 3 | Calculate square of 2 and assert result equals 4 | square = 4 | assertEquals(4, 4) passes | PASS |
| 4 | Test executes with input argument "3" as String | Test method invoked with input = "3" | Integer.parseInt converts "3" to 3 correctly | PASS |
| 5 | Calculate square of 3 and assert result equals 9 | square = 9 | assertEquals(9, 9) passes | PASS |
| 6 | Test executes with input argument "5" as String | Test method invoked with input = "5" | Integer.parseInt converts "5" to 5 correctly | PASS |
| 7 | Calculate square of 5 and assert result equals 25 | square = 25 | assertEquals(25, 25) passes | PASS |
| 8 | All parameterized test cases completed successfully | Test run finished | — | PASS |
@ConvertWith in JUnit parameterized tests?@ConvertWith@ConvertWith annotation tells JUnit which converter class to use to transform the input argument.SimpleArgumentConverter as a base class to extend for custom converters.SimpleArgumentConverter, not implement interfaces or extend unknown classes.@ParameterizedTest
@ValueSource(strings = {"42"})
void testWithConversion(@ConvertWith(MyConverter.class) Integer number) {
System.out.println(number + 8);
}
public class MyConverter extends SimpleArgumentConverter {
@Override
protected Object convert(Object source, Class targetType) {
return Integer.parseInt(source.toString());
}
}public class MyConverter extends SimpleArgumentConverter {
@Override
protected Object convert(Object source, Class targetType) {
if (targetType != Integer.class) {
throw new IllegalArgumentException("Conversion only supports Integer");
}
return source;
}
}"John,25,true" and converts it into a custom Person object with fields name (String), age (int), and active (boolean). Which approach correctly uses argument conversion in JUnit?Pass the test and this pattern moves unknown