Mockito - NullpointerException when stubbing Method

后端 未结 18 1624
半阙折子戏
半阙折子戏 2020-11-30 20:54

So I started writing tests for our Java-Spring-project.

What I use is JUnit and Mockito. It\'s said, that when I use the when()...thenReturn() option I can mock ser

18条回答
  •  伪装坚强ぢ
    2020-11-30 21:06

    The default return value of methods you haven't stubbed yet is false for boolean methods, an empty collection or map for methods returning collections or maps and null otherwise.

    This also applies to method calls within when(...). In you're example when(myService.getListWithData(inputData).get()) will cause a NullPointerException because myService.getListWithData(inputData) is null - it has not been stubbed before.

    One option is create mocks for all intermediate return values and stub them before use. For example:

    ListWithData listWithData = mock(ListWithData.class);
    when(listWithData.get()).thenReturn(item1);
    when(myService.getListWithData()).thenReturn(listWithData);
    

    Or alternatively, you can specify a different default answer when creating a mock, to make methods return a new mock instead of null: RETURNS_DEEP_STUBS

    SomeService myService = mock(SomeService.class, Mockito.RETURNS_DEEP_STUBS);
    when(myService.getListWithData().get()).thenReturn(item1);
    

    You should read the Javadoc of Mockito.RETURNS_DEEP_STUBS which explains this in more detail and also has some warnings about its usage.

    I hope this helps. Just note that your example code seems to have more issues, such as missing assert or verify statements and calling setters on mocks (which does not have any effect).

提交回复
热议问题