junit5

Parameterized Junit 5 with Sting array as source


I have a method that validate passwords. I have a JUnit for that. There I have an array with all possible kind of invalid password. I needed to parameterized the JUnit method using @MethodSource. I guess it should be a way parameterized using directly an String[], INVALID_PASSWORDS, and then I could get rid of the method invalidPasswords():

private static final String[] INVALID_PASSWORDS = { NON_DIGIT_PASSWORD, NON_SPECIAL_CHARACTER_PASSWORD,
        NON_LOWER_CASE_PASSWORD, NON_UPPER_CASE_PASSWORD, SHORTER_THAN_8_PASSWORD, WITH_WHITESPACES_PASSWORD };

@ParameterizedTest
@MethodSource("invalidPasswords")
void When_invalidPassword_Expect_exceptionThrown(String value) {
    Assertions.assertThrows(InvalidRequest.class, () -> Password.of(value.toString()));
}

private static Stream<String> invalidPasswords() {
    return Arrays.stream(INVALID_PASSWORDS);
}

Any idea?


Solution

  • You can use

    @ParameterizedTest
    @ValueSource(strings = { NON_DIGIT_PASSWORD, ... })
    void When_invalidPassword_Expect_exceptionThrown(String value) {
        Assertions.assertThrows(InvalidRequest.class, () -> Password.of(value.toString()));
    }
    

    If you really want a field, you can use @FieldSource:

    static final String[] INVALID_PASSWORDS = { NON_DIGIT_PASSWORD, ... };
    
    @ParameterizedTest
    @FieldSource("INVALID_PASSWORDS")
    void When_invalidPassword_Expect_exceptionThrown(String value) {
        Assertions.assertThrows(InvalidRequest.class, () -> Password.of(value.toString()));
    }