Tags: java spring boot
Want to test smarter, not harder? Parameterized tests let you run the same test with multiple inputs. In this guide, we'll dive into JUnit's @ParameterizedTest
using @MethodSource
and @CsvSource
, plus how to hook it all into Spring Boot.
Using the Spring Initializr:
Go to https://start.spring.io/
Download the project and open it in your IDE with following dependencies
This service contains a method isPalindrome that determines if a given string reads the same backward as forward, ignoring spaces and case sensitivity.
@MethodSource
Instead of writing multiple @Test methods, we’ll use @ParameterizedTest with @MethodSource to provide a stream of test cases.
@ParameterizedTest
: This tells JUnit that this test method will run multiple times with different parameters.
@MethodSource("palindromeProvider")
: This annotation links to a static method (palindromeProvider) that supplies a stream of arguments.
palindromeProvider
: Returns a Stream
"madam" → true
"hello" → false
"A man a plan a canal Panama" → true (after ignoring spaces and case)
Test Logic:
For each set of inputs, the testIsPalindrome method creates an instance of StringService and checks if the output of isPalindrome matches the expected result.
For simpler test cases where you don't need complex data providers, @CsvSource offers a cleaner syntax. You can define your test data directly in the annotation.
How @CsvSource
Works:
Each line inside the annotation represents a test case.
Values are comma-separated and automatically mapped to method parameters.
It's ideal for small, readable test data without needing to write a separate provider method.