简体   繁体   English

使用Mockito返回Java 8可选对象的模拟对象返回Empty Optional

[英]Mocking Object that returns Java 8 Optional Object with Mockito returns Empty Optional

I'm attempting to mock an object that returns a Java Optional object with Mockito: 我正在尝试使用Mockito模拟一个返回Java Optional对象的对象:

SomeObject someObject = new SomeObject();
Mockito.when(someSpringJpaRepository.findById(Mockito.any(UUID.class))).thenReturn(Optional.of(someObject));

When someSpringJpaRepository.findById(UUID) is called, it returns Optional.empty . someSpringJpaRepository.findById(UUID) ,它返回Optional.empty

I'm expecting the method findById() to return someObject . 我期待方法findById()返回someObject
Any reason why it's returning Optional.empty instead? 是什么原因导致它返回Optional.empty

Here is the method: 这是方法:

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();
    }

And here is the Junit: 这是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));
    }

Your @Mock in class is doing nothing. 你班上的@Mock什么也没做。 You created a separate instance of orderRepository which is not injected into your service class. 您创建了一个单独的orderRepository实例,该实例未注入您的服务类。 To inject your mock into context use @MockBean 要将模拟注入上下文,请使用@MockBean

Difference between @Mock and @MockBean here @Mock@MockBean之间的区别在这里

you can try to use spy method 你可以尝试使用间谍方法

Repository spyRepo = Mockito.spy(someSpringJpaRepository);
Mockito.doReturn(Optional.of(someObject)).when(spyRepo).findById(Mockito.any(UUID.class));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM