我正在尝试模拟一个用莫科托返回Java可选对象的对象:
SomeObject someObject = new SomeObject();
Mockito.when(someSpringJpaRepository.findById(Mockito.any(UUID.class))).thenReturn(Optional.of(someObject));
当调用someSpringJpaRepository.findById(UUID)
时,它返回Optional.empty
。
我希望方法findById()
返回someObject
。
它是返回Optional.empty
的任何原因?
这是方法:
public UUID saveOrder(OrderDTO orderDto) {
Order order = new Order();
if (orderDto.getId() != null) {
Optional<Order> result = orderRepository.findById(orderDto.getId());
if (result != null && result.isPresent()) {
order = result.get(); // existing record
} else {
order.setId(UUID.randomUUID());
}
} else {
// new record
order.setId(UUID.randomUUID());
}
return order.getId();
}
这是Junit:
@Test
public void saveOrderTest(){
@Autowired
private OrderApiService orderApiService;
@Mock
private OrderRepository orderRepository;
OrderDTO orderDto = new OrderDTO();
UUID orderID = UUID.randomUUID();
Order order = new Order();
order.setId(orderID);
orderDto.setId(orderID);
Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(Optional.of(order));
assertNotNull(orderApiService.saveOrder(orderDto));
}
您的@Mock
在课堂上什么都不做。您创建了一个单独的orderRepository
实例,该实例未注入您的服务类。将模拟注入上下文中,请使用@MockBean
@Mock
和@MockBean
之间的区别
您可以尝试使用间谍方法
Repository spyRepo = Mockito.spy(someSpringJpaRepository);
Mockito.doReturn(Optional.of(someObject)).when(spyRepo).findById(Mockito.any(UUID.class));