Java 使用 Mockito 模拟界面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36782687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:40:48  来源:igfitidea点击:

Mocking an interface with Mockito

javamockito

提问by Mike

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:

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

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

The implementation of service is:

服务的实现是:

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

My code give NullPoinerException:

我的代码给出 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);
    }
}

回答by Jonathan

I'm guessing that orderis nulland you're getting the NullPointerExceptionhere:

我猜order是这样null,你会得到NullPointerException这里:

when(order.ordersFor(type)).thenReturn(ll);

For @InjectMocksto work and instantiate your class, you'll need to add a runner:

为了@InjectMocks工作和实例化你的类,你需要添加一个跑步者:

@RunWith(MockitoJUnitRunner.class)
public class ServiceImplTest {
    // ...
}

You don't have to use the runner, refer to the documentationfor alternatives.

您不必使用转轮,请参阅文档以获取替代方案。

回答by Sergii Bishyr

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

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

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

如果你想测试,serviceImpl你需要以这种方式模拟:

@Mock
private OrderIF order;

@InjectMocks
private Service reqService = new ServiceImpl(); 

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

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