使用 Mockito 模拟接口

Mocking an interface with Mockito(使用 Mockito 模拟接口)
本文介绍了使用 Mockito 模拟接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

有人可以帮我处理下面的 Mock 对象吗?我想为 ServiceImpl 类编写一个模拟测试用例.我想模拟 OrderIF 接口:

Can someone please help me with the below Mock object. I want to write a mock test case for ServiceImpl class. I want to mock OrderIF interface:

public interface OrderIF{
    List<Order> ordersFor(String type);
}

服务的实现是:

public class ServiceImpl implements Service {
    private List <Order> orders ;
    private OrderIF orderif ; // this is 3rd party interface

    public int getval(String type) {
       //some code 

       // this returns a list of objects (orders)
       orders = orderif.ordersFor(type);

       // some code 
       return orders.get(0)
    }
}

我的代码给出 NullPoinerException:

My code give NullPoinerException:

public class ServiceImplTest {
     private List <Order> ll ;
     private service reqService ; 

     @InjectMocks
     private orderIF order;

     @Before
     public void setUp() throws Exception {
         ll = new ArrayList<Order> ();
         ll.add(new Order("Buy"  ,  11 , "USD" ));
         ll.add(new Order("Sell" ,  22 , "USD" ));
         reqService = spy(new ServiceImpl());
     }

     @Test
     public void test() {
        String type= "USD" ; 
        when(order.ordersFor(type)).thenReturn(ll);
        q = reqService.getval(type);
        assertTrue(q.get().ask == 232.75);
    }
}

推荐答案

@InjectMocks 不会实例化或模拟您的类.此注解用于将模拟注入此字段.

@InjectMocks will not instantiate or mock your class. This annotation is used for injecting mocks into this field.

如果你想测试 serviceImpl 你需要这样模拟:

If you want to test serviceImpl you will need to mock in this way:

@Mock
private OrderIF order;

@InjectMocks
private Service reqService = new ServiceImpl(); 

要使其工作,您需要在 @Before 方法中使用 runner 或 MockitoAnnotations.initMocks(this);.

To make it work you either need to use runner or MockitoAnnotations.initMocks(this); in @Before method.

这篇关于使用 Mockito 模拟接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)