0
0
JUnittesting~5 mins

@ValueSource for simple values in JUnit

Choose your learning style9 modes available
Introduction

@ValueSource helps run the same test many times with different simple inputs. It saves time and avoids repeating code.

You want to check a method with many numbers or strings quickly.
You need to test if a function works for several fixed values.
You want to avoid writing many similar test methods for different inputs.
You want to catch errors that happen only for some specific inputs.
You want to keep your test code clean and easy to read.
Syntax
JUnit
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testWithInts(int number) {
    // test code using number
}

@ValueSource supports simple types like ints, longs, strings, doubles, and chars.

The parameter in the test method must match the type of values in @ValueSource.

Examples
This test runs 3 times, once for each fruit string.
JUnit
@ParameterizedTest
@ValueSource(strings = {"apple", "banana", "cherry"})
void testWithStrings(String fruit) {
    assertNotNull(fruit);
}
This test checks that each number is positive.
JUnit
@ParameterizedTest
@ValueSource(ints = {10, 20, 30})
void testWithInts(int number) {
    assertTrue(number > 0);
}
This test runs for each character and checks it is a letter.
JUnit
@ParameterizedTest
@ValueSource(chars = {'a', 'b', 'c'})
void testWithChars(char letter) {
    assertTrue(Character.isLetter(letter));
}
Sample Program

This test runs 3 times with different words. It checks each word is not empty.

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

public class SimpleValueSourceTest {

    @ParameterizedTest
    @ValueSource(strings = {"hello", "world", "JUnit"})
    void testStringLength(String word) {
        assertTrue(word.length() > 0);
    }
}
OutputSuccess
Important Notes

Use @ValueSource only for simple, single-parameter values.

For multiple parameters, use other providers like @CsvSource.

Keep your test method parameter type matching the @ValueSource type exactly.

Summary

@ValueSource runs one test multiple times with simple values.

It helps test many inputs without repeating code.

Works well for ints, strings, chars, doubles, and longs.