gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:00:12 25 4
gpt4 key购买 nike

在测试期间抛出 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
//...
}
}

最佳答案

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

试试这个:

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

关于java - Mockito.when().thenReturn() 不起作用或返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com