简体   繁体   English

使用 Mockito 模拟接口

[英]Mocking an interface with Mockito

Can someone please help me with the below Mock object.有人可以帮我处理下面的 Mock 对象。 I want to write a mock test case for ServiceImpl class.我想为 ServiceImpl 类编写一个模拟测试用例。 I want to mock OrderIF interface:我想模拟 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);
    }
}

@InjectMocks will not instantiate or mock your class. @InjectMocks不会实例化或模拟您的课程。 This annotation is used for injecting mocks into this field.此注释用于将模拟注入此字段。

If you want to test serviceImpl you 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);要使其工作,您需要使用 runner 或MockitoAnnotations.initMocks(this); in @Before method.@Before方法中。

I'm guessing that order is null and you're getting the NullPointerException here:我猜这个ordernull的,你在这里得到NullPointerException

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

For @InjectMocks to 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 documentation for alternatives.您不必使用跑步者,请参阅文档以获取替代方案。

@InjectMocks doesn't work on interface. @InjectMocks在界面上不起作用。 It needs concrete class to work with.它需要具体的类来使用。

Also @InjectMocks is used to inject mocks to the specified class and @Mock is used to create mocks of classes which needs to be injected.此外, @InjectMocks用于将模拟注入指定的类,@ @Mock用于创建需要注入的类的模拟。

So for your case to work you have to do following change因此,要使您的案例起作用,您必须进行以下更改

@Mock 
private OrderIF order;

@InjectMocks 
private ServiceImpl reqService;

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

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