RandomWits

life is too short for a diary




Mastering Parameterized Tests in JUnit 5 with Spring Boot

Tags: java spring boot

Author
Written by: Tushar Sharma
Featured image for Mastering Parameterized Tests in JUnit 5 with 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.

Set up a Spring Boot project

Using the Spring Initializr:

Creating a Simple Service

This service contains a method isPalindrome that determines if a given string reads the same backward as forward, ignoring spaces and case sensitivity.

Parameterized Tests with @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 where each Arguments.of() represents a test case. For example:

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

CSV Source

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.


comments powered by Disqus