使用mockito

时间:2018-06-17 04:16:02

标签: junit mocking mockito

我在用超级方法模拟调用超级类方法时遇到了问题。代码如下所示。

public class OrderBOSuperImpl {

    public boolean placeOrder(Order order) throws BOException {
        test();
        return true;
    }

    public void test(){

    }
}

在子类中实现

public class OrderBOImpl extends OrderBOSuperImpl implements OrderBO {

    private OrderDAO dao;

    @Override
    public boolean placeOrder(Order order) throws BOException {
        try {

            super.placeOrder(order);

            int result = dao.create(order);

            if (result == 0) {
                return false;
            }
        } catch (SQLException e) {
            throw new BOException(e);
        }

        return true;
    }
}

测试

public class OrderBOImplTest {

    @Mock
    OrderDAO orderDAO;
    private OrderBOImpl orderBO;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);
        orderBO = spy(new OrderBOImpl());
        orderBO.setDao(orderDAO);
    }

    @Test
    public void placeOrderShouldCreateAnOrder() throws SQLException, BOException {
        Order order = new Order();
        doReturn(true).when((OrderBOSuperImpl)orderBO).placeOrder(order);
        Mockito.when(orderDAO.create(order)).thenReturn(new Integer(1));
        boolean result = orderBO.placeOrder(order);
        assertTrue(result);
        Mockito.verify(orderDAO).create(order);
    }
}

错误:

  

通缉但未调用:orderDAO.create(       com.test.order.dto.Order@544fe44c);    - >在OrderBOImplTest.placeOrderShouldCreateAnOrder(OrderBOImplTest.java:42)   实际上,这个模拟没有互动。

     

通缉但未调用:orderDAO.create(       com.test.order.dto.Order@544fe44c);    - >在OrderBOImplTest.placeOrderShouldCreateAnOrder(OrderBOImplTest.java:42)   实际上,这个模拟没有互动。

     

在   OrderBOImplTest.placeOrderShouldCreateAnOrder(OrderBOImplTest.java:42)

我注意到的是,如果我将超类方法的名称从placeOrder更改为其他名称,并在没有" super的情况下调用该方法。"在子类测试中可以成功模拟超类方法。无论如何我只能使用mockito在这种情况下嘲笑超类方法吗?

0 个答案:

没有答案