0
0
JUnittesting~3 mins

Why @ValueSource for simple values in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could test many inputs with just one simple method and no copy-pasting?

The Scenario

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.

The Problem

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.

The Solution

@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.

Before vs After
Before
void testWithOneValue() { assertTrue(isValid(1)); }
void testWithAnotherValue() { assertTrue(isValid(2)); }
After
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testWithMultipleValues(int number) {
  assertTrue(isValid(number));
}
What It Enables

You can easily test many input values with one clean, simple test method, making your tests faster to write and easier to understand.

Real Life Example

Testing a password validator with different password lengths or characters to ensure it works correctly for all cases without writing many separate tests.

Key Takeaways

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.