Mockito.when()。thenReturn()不起作用或返回null

时间:2016-05-03 18:07:01

标签: java mockito optional

在测试期间抛出NullPointerException。我试图调试它,我唯一能解决的是eventOptional总是为null。就像Mockito.when()。thenReturn()没有工作一样。有人可以帮忙吗?这是我测试服务和测试本身的代码:

@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));
        //...
    }
}

测试类:

@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
        //...
    }
}

2 个答案:

答案 0 :(得分:1)

看起来问题是initMock被调用了两次:一次是由跑步者,一次是setUp方法。使用常规跑步者运行测试或从initMocks方法移除setUp调用可解决此问题。

答案 1 :(得分:0)

我遇到了同样的错误,尝试了很多事情之后,我通过用any()替换了anyString()方法来修复了它

尝试一下:

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