Mockito.when().thenReturn() doesn't work or returns null

混江龙づ霸主 提交于 2020-01-03 16:57:28

问题


During the test there is a NullPointerException thrown. I tried to debug it and the only thing I worked out was that eventOptional is always null. Just as if Mockito.when().thenReturn() didn't work. Can anybody help? Here's my code for a tested service and for the test itself:

@Service
public class EventService {

    @Autowired 
    public EventService(EventRepository eventRepository) {
        this.eventRepository = eventRepository;
    }
    //...
    public void updateEvent(EventDTO eventDTO) {
        Optional<Event> eventOptional = eventRepository.findOneById(eventDTO.getId());

        eventOptional.orElseThrow(() -> new BadRequestException(EVENT_NOT_FOUND));
        //...
    }
}

And the test class:

@RunWith(MockitoJUnitRunner.class)
public class EventServiceTest {

    @Mock
    private EventRepository eventRepository;
    @InjectMocks
    private EventService eventService;

    private Event sampleEventFromDb;

    @Before
    public void setUp() throws Exception {

        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void shouldUpdateEventTestAndWithProperTime() throws Exception {
        EventDTO eventDTOMock = Mockito.mock(EventDTO.class);

        sampleEventFromDb = Event.builder()
            .name("name")
            .startDateTime(LocalDateTime.now())
            .placeName("place")
            .description("description")
            .publicEvent(true)
            .owner(new User())
            .build();

        Mockito.when(eventRepository.findOneById(anyString())).thenReturn(Optional.of(sampleEventFromDb));
        Mockito.when(eventDTOMock.getId()).thenReturn("1");

        eventService.updateEvent(eventDTOMock); //NullPointerException
        //...
    }
}

回答1:


Looks like the problem is that initMock is called twice: once by the runner and once by the setUp method. Running the test with the regular runner or removing the initMocks call from the setUp method fixes this problem.




回答2:


I got this same error, after trying a lot of things I fixed it by replacing the anyString() method with any()

Try this:

Mockito.when(eventRepository.findOneById(any())).thenReturn(Optional.of(sampleEventFromDb));



来源:https://stackoverflow.com/questions/37011328/mockito-when-thenreturn-doesnt-work-or-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!