Sub topic 3
Running One Test with Many Inputs
This chapter gives a quick tour of the JUnit 5 tools you will reach for once your basic tests work.
Running One Test with Many Inputs
A parameterized test is a test method that runs once for each set of inputs you give it. Instead of writing three almost identical tests, you write one test and a list of inputs.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CalculatorParameterizedTest {
private final Calculator calculator = new Calculator();
@ParameterizedTest
@CsvSource({
"1, 1, 2",
"2, 3, 5",
"-4, 4, 0"
})
void addHandlesManyInputs(int a, int b, int expected) {
assertEquals(expected, calculator.add(a, b));
}
}Each row in @CsvSource is one run of the test. JUnit turns the columns into a, b, and expected.
More Tools at a Glance
| Feature | What it does | Example |
|---|---|---|
| `@Disabled` | Skips a test | `@Disabled("bug #42")` |
| `@Tag` | Labels a test so you can run groups of tests | `@Tag("slow")` |
| Assumption | Skips a test when a condition is false | `assumeTrue(isLinux)` |
| `@Nested` | Puts related tests in an inner class | `@Nested class WhenEmpty { }` |
| `@Timeout` | Fails a test that runs too long | `@Timeout(2)` (seconds) |
| `@TempDir` | Gives the test a temporary folder that JUnit deletes afterwards | `@TempDir Path dir;` |
| Mock | A fake object that stands in for a real one | `@Mock PriceRepository prices;` |
| `@ExtendWith` | Adds extra behavior to JUnit | `@ExtendWith(MockitoExtension.class)` |
A mock is a fake object, usually made with the Mockito library. It lets you test one class without its real database or network. You tell the mock what to return, for example when(prices.priceOf("apple")).thenReturn(3).
An extension is a plug-in that hooks into JUnit. Mockito's extension creates your @Mock fields before each test runs.
Writing Tests That Stay Useful
- Keep tests fast so you run them often.
- Make each test independent, so it never relies on another test running first.
- Make tests repeatable, so they give the same result every time. Avoid using real clocks, random values, or the network.
- Test one behavior per test and give the test a name that says what that behavior is.
Coming from JUnit 4
Exercise
You want one test to check that add(0, 0) returns 0 and add(10, 5) returns 15. Which two annotations do you need, and what are the CSV rows?
Show answer
Use @ParameterizedTest and @CsvSource, with the rows "0, 0, 0" and "10, 5, 15".
Exercise
A test reads a real file from your project folder and sometimes fails on other computers. Which JUnit feature fixes this?
Show answer
@TempDir. The test creates its own file inside a temporary folder, so it never depends on real project files.