我正在尝试模拟一个对象,该对象使用Mockito返回一个Java Optional对象:
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));
}
答案 0 :(得分:2)
您在课堂上的def Email(values, search):
x = list()
for i in values:
if i.endswith("@" + search):
x.append(i)
return ", ".join(x) # Returning list as a comma separated value
emails = ["email@example.com","email1@example.com","email2@example.com","emaila@emailexample.com","emailb@emailexample.com","email33@examplex.com","emailas44@exampley.com","emailoi45@exampley.com","emailgh@exampley.com"]
website = 'example.com'
data = Email(emails, website)
print("Website = " + website)
print("Email = " + data)
无所作为。您创建了@Mock
的单独实例,该实例未注入您的服务类中。要将模拟插入上下文,请使用orderRepository
@MockBean
和@Mock
here之间的差异
答案 1 :(得分:1)
您可以尝试使用间谍方法
Repository spyRepo = Mockito.spy(someSpringJpaRepository);
Mockito.doReturn(Optional.of(someObject)).when(spyRepo).findById(Mockito.any(UUID.class));