JUnit @ParametrizedTest Class Objects as Value Source?

Viewed 1209

I would like to create a ParametrizedTest that tests a bunch of different AIs at the same time, making sure that the don't take too long to do their calculations. However, I cannot create new Objects in the ValueSource, so I'm unsure how to proceed.

The problem is that I need to pass constant values to ValueSource, which is where I get stuck. How can I make my objects constant?


 @ParameterizedTest
  @ValueSource(ais = {new AdvancedAI(), new blabla})
  public void moveCalculatedInTimeBy(AI TestAI) {
    long startTime = System.currentTimeMillis();
    Turn turn = Turn.initialTurn();
    Move calculatedMove = TestAI.calculateMove(Optional.empty(), turn);
    long endTime = System.currentTimeMillis() - startTime;
    assertTrue(endTime <= 8000);
  }

1 Answers

Using @ValueSource is for simple arguments, the kind that can be set as values to annotation elements. In other words, primitives, strings, and classes1. Since you want to provide instances of a class this won't work for you. Instead, you'll want to use something like @MethodSource2.

@ParameterizedTest
@MethodSource("testAiProvider")
void moveCalculatedInTimeBy(AI testAI) {
  // perform test...
}

static List<AI> testAiProvider() {
  // return List of test AI instances
}

See the user guide and Javadoc for more information, such as what return types are allowed for factory methods.


1. Enum constants can also be used in annotations, but you can't make a generic enum annotation element. That's why JUnit 5 also has @EnumSource.

2. You can also use @ArgumentsSource directly, which lets you define an ArgumentsProvider, if you need it.

Related