Search code examples
javajunit5parameterized

JUnit 5 @ParameterizedTest with using class as @ValueSource


I want to do a ParameterizedTest with @ValueSource , i have readed many tutorials including Guide to JUnit 5 Parameterized Tests:

/**
 * The {@link Class} values to use as sources of arguments; must not be empty.
 *
 * @since 5.1
 */
Class<?>[] classes() default {};

So i tried the following :

@ParameterizedTest
@ValueSource(classes = {new Mandator("0052", "123456", 79)})
void testCalculateMandateI(Mandator value) {

     //code using Mandator here
}

Mandator class:

 public class Mandator {

    private String creditorPrefix;
    private String retailerCode;
    private int mandateIdSequence;

    public Mandator(final String creditorPrefix, final String retailerCode, final int mandateIdSequence) {
        this.creditorPrefix = creditorPrefix;
        this.retailerCode = retailerCode;
        this.mandateIdSequence = mandateIdSequence;
    }

    public String getCreditorPrefix() {
        return creditorPrefix;
    }

    public String getRetailerCode() {
        return retailerCode;
    }

    public int getMandateIdSequence() {
        return mandateIdSequence;
    }
}

But i get the following error from IntelliJ , hovering above @ValueSource :

enter image description here

Attribute value must be a constant

What am i doing wrong here ? What am i missing ?


Solution

  • Its not about JUnit but about Java Syntax.

    Its impossible to create new objects in parameters of the annotations.

    The type of an annotation element is one of the following:

    • List A primitive type (int, short, long, byte, char, double, float, or boolean)
    • String
    • Class (with an optional type parameter such as Class)
    • An enum type
    • An annotation type
    • An array of the preceding types (an array of arrays is not a legal element type)

    If you want to supply values out of created objects consider using something like this as one possible solution:

    @ParameterizedTest
    @MethodSource("generator")
    void testCalculateMandateI(Mandator value, boolean expected)
    
    // and then somewhere in this test class  
    private static Stream<Arguments> generator() {
    
     return Stream.of(
       Arguments.of(new Mandator(..), true),
       Arguments.of(new Mandator(..), false));
    }