7

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
        //...
    }
}
HectorBarbossa
  • 185
  • 1
  • 3
  • 9
  • 1
    You dont need to do MockitoAnnotations.initMocks(this) if running the test with the MockitoJUnitRunner. Also make sure that the findOneById method is not declared as static, private or final. – mdewit May 03 '16 at 18:37
  • @SotiriosDelimanolis, it is initialized by the runner and/or initMocks using reflection. And it is, in fact, initialized in this example—I've just checked. The funny thing is, works fine for me with TestNG, but fails with JUnit. This is certainly not a duplicate so I've voted to reopen. – Sergei Tachenov May 03 '16 at 18:40
  • Actually when I just gave up on MockitoJunitRunner and mocked repository manually as well as initialized the service via its constructor - it works now perfectly. – HectorBarbossa May 03 '16 at 18:44
  • @mdewit, looks like you hit the spot—removing either the runner or the `initMocks` call fixes the problem, but why? `initMocks` is not idempotent? – Sergei Tachenov May 03 '16 at 18:44
  • @Sergey Tachenov That is interesting, I did not actually think it would fix the problem just thought it was unnecessary to use both. As MockitoAnnotations.initMocks only needs to be used if you want to run with a different runner than MockitoJUnitRunner (such as the Junit Parameterized runner). – mdewit May 03 '16 at 18:51
  • @mdewit, neither did I. I've discovered it purely because I tried to run this first with TestNG and saw no problems. But then I thought, “Oh, but there is no JUnitRunner in TestNG, don't tell me...” – Sergei Tachenov May 03 '16 at 18:52

3 Answers3

14

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));

Hugo Lezama
  • 198
  • 2
  • 7
8

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.

Sergei Tachenov
  • 24,345
  • 8
  • 57
  • 73
0

Change anyList(), anyMap()..... to any(). After long debugging it is worked finally.