Search code examples
javajunitmockitojunit5

Mockito parametrize methodCall in mockito


@ExtendWith(MockitoExtension.class)
public class MyServiceTest
{
   @Mock
   private static MyRepository myRepository;
   private MyService myService;

   @BeforeEach
   void setUp()
   {
      myService = new MyService(myRepository);
   }

@ParameterizedTest
   @ArgumentsSource(TestParameter.class)
   void findAllTest(Map<String, String> allParamaters, Object methodCall) throws JsonProcessingException
   {

      Element element = Element.builder().identification("id").build();

      // how to pass different methodCall according to parametrized tests
      when(methodCall).thenReturn(List.of(element));

      var expectedResponse = myService.excute(allParamaters);

      //assert....;
   }

   private static class TestParameter implements ArgumentsProvider
   {
private static final MyRepository myRepository = mock(MyRepository.class); 
      @Override
      public Stream<? extends Arguments> provideArguments(ExtensionContext context)
      {
         return Stream.of(
                  Arguments.of(Map.of("key_1", "value_2", myRepository.findComponentByKey_1(....)),
                  Arguments.of(Map.of("key_1", "value_2", myRepository.findComponentByKey_2(....)),
         );
      }
   }

how to pass different methodCall according to parametrized tests to when. I always return the same list of elements


Solution

  • As the methods you want to stub always return List<Element> , you can use Supplier<List<Element>> to represent a method call. Also use @MethodSource to define the parameters is easier and cleaner than ArgumentsProvider IMO.

    
    @ParameterizedTest
    @MethodSource("args")
    void findAllTest(Map<String, String> allParamaters, Supplier<List<Element>> methodCall) {
    
     when(methodCall.get()).thenReturn(List.of(element));
     var expectedResponse = myService.excute(allParamaters);
    
    }
    
    private static Stream<Arguments> args() {
    
       Supplier<List<Element>> find1 = () -> myRepository.findComponentByKey_1(...);
       Supplier<List<Element>> find2 = () -> myRepository.findComponentByKey_2(...);
    
       return Stream.of(
               Arguments.of(Map.of("k1", "v1"), find1),
               Arguments.of(Map.of("k2", "v2"), find2)
       );
    }