我有一个简单的类,我想模拟它:
总线层:
/**
* Created by Alexandr on 14.05.2016.
*/
public class BusineesLayer {
public OrderModel orderModel;
public DbService dbService;
...
public BusineesLayer(OrderModel orderModel,DbService dbService) {
this.orderModel = orderModel;
dbService = dbService;
}
public BusineesLayer() {
}
public boolean checkItemsInDb(List<Items> items) throws HandleOrderExeption {
...
return result
}
public boolean handleOrder() throws HandleOrderExeption {
checkItemsInDb(orderModel.getItemsList());
boolean res =dbService.addOrder(orderModel.getItemsList(),
orderModel.getCustumerName(),
countTotalSum(orderModel.getItemsList())
);
return res;
}
}
我想测试hanldeOrder()
方法,为了减少调用"true"内部checkItemsinDb()的过量;
所以,我的测试看起来是这样的:
@Test
public void handleorderTest() {
...
BusineesLayer layer = Mockito.mock(BusineesLayer.class);
layer.dbService = busineesLayer.dbService;
layer.orderModel = busineesLayer.orderModel;
Mockito.when(layer.checkItemsInDb()).thenReturn(true);
boolean res = layer.handleOrder();
assertThat(res, equalTo(true));
}
但是它总是返回false并且根本不通过handlOrder()
有什么办法解决吗?或者我如何重构我的代码来测试它?
您不测试mock,而是使用mock来帮助您进行测试。
我想你只是对如何使用mock感到困惑。Mock允许我们模拟并可以响应我们正在测试的对象。如果您正在测试handleOrder
方法,那么您应该模拟与该方法交互的任何东西,在本例中是DbService
和OrderModel
。
@Test
public void handleorderTest() {
BusineesLayer layer = new BusineesLayer(); //we are testing this!
DbService dbService = Mockito.mock(DbService.class);
OrderModel orderModel = Mockito.mock(OrderModel.class);
layer.dbService = dbService;
layer.orderModel = orderModel;
Mockito.when(orderModel.getItemsList()).thenReturn(new ArrayList<Items>());
Mockito.when(dbService.foo()).thenReturn(true);
//mock up multiple calls so your service will provide true
boolean res = layer.handleOrder();
assertThat(res, equalTo(true));
//repeat for false, and so on
}
但是,如果您正在尝试测试dbService
调用,那么您应该为它创建一个完全没有业务层的测试。业务层不依赖于任何东西,除了对其他方法的调用,所以无论您使用那些真实的对象还是这些对象的模拟版本,功能都应该是相同的。只有当DBService或OrderModel中断时,业务逻辑才会出现故障,因此您将单独测试服务和模型(不涉及业务层)来测试它们。