Junit 5 parameterized test with Class @ValueSource

This is a follow up to a previous blog post I wrote about Junit 5 parameterized tests. The @ValueSource annotation allows you to specify an array of literal values where a single value is used per invocation of the test. @ValueSource handles all the primitives, String and Class object. The Junit 5 user guide does not have an example of how to use a java.lang.Class @ValueSource.

I have used it to test exception handling. For example, in the following test, it verifies that both JPA and Spring DAO exception for no matching database row are mapped to the OrderNotFoundException. (The exception is annotated with Spring web’s @ResponseStatus to map to the HTTP status 404 NOT FOUND).

@ParameterizedTest
@ValueSource(classes = {NoResultException.class, EmptyResultDataAccessException.class})
  public void testOrderNotFound(Class<? extends Exception> clazz) throws Exception {
    when(orderDao.getOrder(ORDER_ID)).thenThrow(clazz);
    assertThrows(OrderNotFoundException.class,
        () -> provisionService.addNumbers(ORDER_ID, USER));
}