Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit 5 @ParameterizedTest with using class as @ValueSource [duplicate]

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 ?

like image 541
GOXR3PLUS Avatar asked Mar 21 '26 15:03

GOXR3PLUS


1 Answers

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));
}
like image 53
Mark Bramnik Avatar answered Mar 24 '26 06:03

Mark Bramnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!