如何正确使用嘲笑

时间:2016-05-16 18:19:32

标签: java unit-testing mockito

我有愚蠢的课程,我想嘲笑:

BusineesLayer:

/**
 * 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()方法,以便在invoke&#34; true&#34;;

中使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()

有什么方法可以解决吗?或者我如何重构我的代码来测试它呢?

1 个答案:

答案 0 :(得分:1)

你不测试嘲笑,你使用模拟来帮助你测试。

我认为你对如何使用模拟感到困惑。模拟允许我们模拟并可以响应我们正在测试的对象。如果您正在测试handleOrder方法,那么您应该模拟与该方法交互的任何内容,在本例中为DbServiceOrderModel

@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中断,业务逻辑似乎只会失败,因此您将分别测试服务和模型(不涉及业务层)来测试它们。