Parametrize List of Object with Junit 5

Viewed 758

I would like to parametrize test, with Junit 5, which should call such method:

service.doSomething(List<Person> persons, int amount);

Assume that Person class look like that:

Class Person {
   PersonId id;
   String name;
}

Problem is with a List <Person>. I'm not sure how should I parametrize that, use some converter to convert Person values to some primitice or use ArgumentsAgrragator? Additionaly Person conain another Object (PersonId) which need to be handled as well.

Do you have some advices for me how to do that?

1 Answers

If you only need this parametrization in one test class, you can use @MethodSource to provide a stream of parameter sets of any complexity, e.g.:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.List;
import java.util.stream.Stream;

import static org.junit.jupiter.params.provider.Arguments.arguments;

...

@ParameterizedTest
@MethodSource("doSomethingArgsProvider")
public void testServiceDoSomething(final List<Person> persons, final int amount) {
    // preparations

    service.doSomething(persons, amount);

    // assertions
}

static Stream<Arguments> doSomethingArgsProvider() {
    final var person1 = new Person(new PersonId(1), "John");
    final var person2 = new Person(new PersonId(2), "Jane");

    return Stream.of(
        arguments(List.of(person1), 1),
        arguments(List.of(person1, person2), 2),
    );
}

If you want to create a re-usable, complex parameter source for multiple tests, you can implement your own ArgumentsProvider and use it with @ArgumentsSource.

Related