What if you could test many inputs with just one simple method and no copy-pasting?
Why @ValueSource for simple values in JUnit? - Purpose & Use Cases
Imagine you have a function that needs to be tested with many different input values. You write a separate test method for each value, repeating almost the same code again and again.
This manual way is slow and boring. It's easy to make mistakes by copying and pasting. Also, if you want to add more test values, you have to write even more methods, making your test code messy and hard to maintain.
@ValueSource lets you run the same test method multiple times with different simple values automatically. You write the test once and just list the values. JUnit takes care of running the test for each value, saving time and avoiding errors.
void testWithOneValue() { assertTrue(isValid(1)); }
void testWithAnotherValue() { assertTrue(isValid(2)); }@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testWithMultipleValues(int number) {
assertTrue(isValid(number));
}You can easily test many input values with one clean, simple test method, making your tests faster to write and easier to understand.
Testing a password validator with different password lengths or characters to ensure it works correctly for all cases without writing many separate tests.
Manual tests for each value are slow and repetitive.
@ValueSource runs one test multiple times with different values.
This makes tests simpler, cleaner, and less error-prone.