Search code examples
javaunit-testingjunitjunit5

Pass externally defined variable to JUnit @ValueSource annotation in a @ParameterizedTest


I have an array of strings that I would like to use for multiple unit tests. In an effort to de-duplicate my code and to minimize the number of changes I would need to make to my test parameters in the future, I have tried defining a variable within my JUnit test class and then re-using this variable as the input parameter for each of my @ValueSource annotations. Is this even possible or am I overlooking a simple mistake?

private static final String[] myParameters = {"a", "b", "c"};

// This fails with the message that `myParameters` isn't a recognized symbol, probably because it's not a valid Element for @ValueSource
@ParameterizedTest
@ValueSource(myParameters)
public void myTest(String param) {
  // doesn't compile
}

// This fails with the message that "incompatible types: String[] cannot be converted to String"
@ParameterizedTest
@ValueSource(strings = myParameters)
public void myTest(String param) {
  // doesn't compile
}

// This works fine, but I would need to duplicate the values of `strings` for each test
@ParameterizedTest
@ValueSource(strings = {"a", "b", "c"})
public void myTest(String param) {
  // works fine, but its duplicative in terms of the @ValueSource parameter
}

References:


Solution

  • I suggest you use a @MethodSource to wrap your constant:

    private static final String[] myParameters = {"a", "b", "c"};
    
    static List<String> myParameters() {
        return Arrays.asList(myParameters);
    }
    
    @ParameterizedTest
    @MethodSource("myParameters")
    public void myTestWithMethodSource(String param) {
        System.out.println(param);
    }