Imagine you have multiple tests that check the same logic but with different input values. How does parameterization help reduce duplication in such cases?
Think about how you can reuse the same code but test different values.
Parameterization lets you write one test method that runs multiple times with different inputs. This avoids copying the same test code multiple times for each input, reducing duplication.
Given this JUnit 5 parameterized test, what will be the output when running it?
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertTrue; class SampleTest { @ParameterizedTest @ValueSource(strings = {"racecar", "radar", "hello"}) void testPalindrome(String word) { assertTrue(new StringBuilder(word).reverse().toString().equals(word)); } }
Check which input strings are palindromes.
The test runs three times with inputs 'racecar', 'radar', and 'hello'. The first two are palindromes, so they pass. The last input 'hello' is not a palindrome, so the test fails on that run.
Which assertion correctly verifies that a number is even inside a JUnit parameterized test?
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertTrue; class NumberTest { @ParameterizedTest @ValueSource(ints = {2, 4, 5, 8}) void testEven(int number) { // Which assertion is correct here? } }
Think about how to check if a number is even using modulo.
To check if a number is even, the remainder when divided by 2 should be zero. So number % 2 == 0 is true for even numbers. The assertion assertTrue(number % 2 == 0) correctly verifies this.
Look at this JUnit 5 parameterized test code. Why does it fail to run any tests?
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; class DebugTest { @ParameterizedTest @ValueSource(strings = {"apple", "banana"}) void testFruit() { System.out.println("Fruit test"); } }
Check the method signature and parameters.
The parameterized test method must accept a parameter of the type provided by @ValueSource. Here, the method testFruit() has no parameters, but @ValueSource provides strings. This mismatch causes the test not to run.
In JUnit 5, when using @ParameterizedTest with multiple inputs, how does the test runner execute the tests?
Think about how parameterized tests show results in test reports.
JUnit 5 runs the parameterized test method once for each input value separately. Each run is reported as an individual test case in the test report, allowing clear visibility of which inputs passed or failed.