0
0
JunitHow-ToBeginner ยท 3 min read

How to Use @ValueSource in JUnit for Parameterized Tests

Use @ValueSource in JUnit to provide a list of literal values to a parameterized test method. Annotate the test method with @ParameterizedTest and pass the values inside @ValueSource to run the test multiple times with different inputs.
๐Ÿ“

Syntax

The @ValueSource annotation is used with @ParameterizedTest to supply an array of literal values to a test method parameter. Supported types include ints, strings, longs, doubles, and chars.

Example parts:

  • @ParameterizedTest: Marks the method as a parameterized test.
  • @ValueSource(ints = {1, 2, 3}): Supplies integer values 1, 2, and 3 to the test.
  • Method parameter: Receives each value in turn during test execution.
java
@ParameterizedTest
@ValueSource(strings = {"apple", "banana", "cherry"})
void testWithStrings(String fruit) {
    // test code using fruit
}
๐Ÿ’ป

Example

This example shows a parameterized test that checks if the input string is not empty. The test runs once for each string provided by @ValueSource.

java
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;

class FruitTest {

    @ParameterizedTest
    @ValueSource(strings = {"apple", "banana", "cherry"})
    void testNotEmptyString(String fruit) {
        assertNotNull(fruit);
        assertFalse(fruit.isEmpty());
    }
}
Output
Test run successful: 3 tests passed.
โš ๏ธ

Common Pitfalls

  • Forgetting to annotate the test method with @ParameterizedTest causes @ValueSource to be ignored.
  • Using unsupported types in @ValueSource leads to compilation errors; only primitive arrays and strings are allowed.
  • Method parameters must match the type of values supplied by @ValueSource.
  • Trying to use multiple parameters with @ValueSource alone is not possible; use @CsvSource or other providers instead.
java
/* Wrong: Missing @ParameterizedTest */
@ValueSource(ints = {1, 2, 3})
void testNumbers(int number) {
    assertTrue(number > 0);
}

/* Right: Add @ParameterizedTest */
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testNumbers(int number) {
    assertTrue(number > 0);
}
๐Ÿ“Š

Quick Reference

@ValueSource supports these value types:

Value TypeExample Usage
int@ValueSource(ints = {1, 2, 3})
long@ValueSource(longs = {10L, 20L})
double@ValueSource(doubles = {1.5, 2.5})
char@ValueSource(chars = {'a', 'b', 'c'})
String@ValueSource(strings = {"foo", "bar"})
โœ…

Key Takeaways

Annotate test methods with @ParameterizedTest to enable parameterized testing.
Use @ValueSource to supply simple literal values like ints, strings, or chars.
Ensure the method parameter type matches the type of values in @ValueSource.
You cannot use multiple parameters with @ValueSource; use other providers for that.
Always include @ParameterizedTest; @ValueSource alone does not run tests.