Simple way to have two values as ValueSource for Junit5 ParameterizedTest

2k Views Asked by At

I have many boolean methods like boolean isPalindrome(String txt) to test.

At the moment I test each of these methods with two parameterised tests, one for true results and one for false results:

    @ParameterizedTest
    @ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" })
    void test_isPalindrome_true(String candidate) {
        assertTrue(StringUtils.isPalindrome(candidate));
    }
    
    @ParameterizedTest
    @ValueSource(strings = { "peter", "paul", "mary is here" })
    void test_isPalindrome_false(String candidate) {
        assertFalse(StringUtils.isPalindrome(candidate));
    }

Instead I would like to test these in one parameterised method, like this pseudo Java code:

    @ParameterizedTest
    @ValueSource({ (true, "racecar"),(true, "radar"), (false, "peter")})
    void test_isPalindrome(boolean res, String candidate) {
        assertEqual(res, StringUtils.isPalindrome(candidate));
    }

Is there a ValueSource for this? Or is there an other way to achieve this in a concise manner?

1

There are 1 best solutions below

0
halloleo On

Through the very helpful comment from Dawood ibn Kareem (on the question) I got a solution involving @CsvSource:

    @ParameterizedTest
    @CsvSource(value = {"racecar,true", 
                        "radar,true", 
                        "peter,false"})
    void test_isPalindrome(String candidate, boolean expected) {
        assertEqual(expected, StringUtils.isPalindrome(candidate));
    }

I quite like: Although the code uses strings to express boolean types, it is quite compact and keeps things together which IMHO belong together.

Read about @CsvSource here.