Search code examples
javajunitmockitoparameter-passingjunit5

NullPointerException Parameterized Test passing input using Mockitos


@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, List<Element> methodCall) throws JsonProcessingException
   {

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

      when(methodCall).thenReturn(List.of(element));

      var expectedResponse = myService.excute(allParamaters);

      //assert....;
   }

   private static class TestParameter implements ArgumentsProvider
   {
      @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(....)),
         );
      }
   }

i get a NullPointerException of myRepository in provideArguments(ExtensionContext context).


Solution

  • you are using myRepository.findComponentByKey_1()

    to build your arguments stream but your repository is not initialized at this point.

    First your TestParameter class will be initalized to be passed into a function. It will happen before @Mock annotation will work to mock an instance of your repository

    Then your repository will be initialized by @Mock

    Then your @BeforeEach function will fire

    And lastly your test function will be called

    I hope that clears things for you.

    Edit:

    You could add another function with annotation @BeforeAll it needs to be static then inside that you need to manually mock your repository and it should work since @BeforeAll function will fire before generating argument source

    myRepository = mock(MyRepository.class);