简体   繁体   中英

JUnit @ParametrizedTest Class Objects as Value Source?

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);
  }

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

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM