使用 Mockito 模拟接口

2022-09-01 11:02:17

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

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:

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

答案 1

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

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

@Mock
private OrderIF order;

@InjectMocks
private Service reqService = new ServiceImpl(); 

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


答案 2

我猜那是,你得到这里:ordernullNullPointerException

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

要使类正常工作和实例化,您需要添加一个运行器:@InjectMocks

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

您不必使用跑步者,请参阅文档以了解替代方案。


推荐