Mockito.when().thenReturn()不起作用或返回null [英] Mockito.when().thenReturn() doesn't work or returns null
问题描述
在测试期间,将引发NullPointerException.我尝试对其进行调试,但我得出的唯一结论是eventOptional始终为null.就像Mockito.when().thenReturn()无法正常工作一样.有人可以帮忙吗?这是我用于测试服务和测试本身的代码:
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));
//...
}
}
和测试类:
@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
//...
}
}
推荐答案
问题似乎是initMock
被调用了两次:一次由运行器调用,一次由setUp
方法调用.使用常规运行程序运行测试或从setUp
方法中删除initMocks
调用即可解决此问题.
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.
这篇关于Mockito.when().thenReturn()不起作用或返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!