使用 Mockito 模拟接口
有人可以帮我下面的模拟对象。我想为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);
}
}