如何使用参数(Object [] {})模拟jdbcTemplate.query

时间:2019-06-26 21:48:17

标签: java unit-testing mocking mockito jdbctemplate

我正在尝试使用Mockito模拟jdbcTemplate并调用方法查询,该查询使用Object [] {}传递参数。

我正在对我的DAO层进行单元测试,我想模拟jdbcTemplate并调用方法查询并使用Object [] {} {}

传递sql字符串,RowMapper和参数
public List<EntityType> myDaoMethod(Date fechaInicio, Date fechaFin)
            throws NotDataFoundException {
        log.info("entering => myDaoMethod");
        log.info("param => fechaInicio :" +  fechaInicio);
        log.info("param => fechaFin :" +  fechaFin);

        log.debug("Se ejecutando consulta...");
        try {

            List<EntityType> query = jdbcTemplate.query(QueryStrs.MY_QUERY,
                    new Object[] {fechaInicio, fechaFin},
                    new BeanPropertyRowMapper<EntityType>(EntityType.class));
            log.debug("Se ejecuto consulta. ");

            return query;
        }catch(DataAccessException e) {
            log.error("No se encontro informacion en la consulta myDaoMethod (2)", e);
            throw new NotDataFoundException(e);
        }finally {
            log.info("exiting => myDaoMethod");
        }
    }
    @Mock
    private JdbcTemplate jdbcTemplate;

        @Test
    public void myTestMethod() throws NotDataFoundException {

        List<EntityType> listValue = new ArrayList<>();

        listValue.add(new EntityType((short) 2, "modem 2"));
        listValue.add(new EntityType((short) 1, "modem"));

        when(jdbcTemplate.query(any(String.class),any(Object[].class), any(BeanPropertyRowMapper.class))).thenReturn(listValue);

        MyDao dao = new MyDaoImpl(jdbcTemplate);
        List<EntityType> otrasAdicionalesPorRangoFecha = dao.myDaoMethod(any(Date.class), any(Date.class));

        Assert.assertNotNull(otrasAdicionalesPorRangoFecha);
        Assert.assertTrue(!otrasAdicionalesPorRangoFecha.isEmpty());
//      Assert.assertArrayEquals(listValue.toArray(), otrasAdicionalesPorRangoFecha.toArray());

    }

跟踪结果是

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 无效使用参数匹配器! 预期有3个符合条件的记录,有2个记录: -> com.oracle.reporter.tddtest.rrhhcomision.OtrasAdicionalesDaoTest.testBuscarOtrasAdicionalesPorFecha(OtrasAdicionalesDaoTest.java:80) -> com.oracle.reporter.tddtest.rrhhcomision.OtrasAdicionalesDaoTest.testBuscarOtrasAdicionalesPorFecha(OtrasAdicionalesDaoTest.java:80)

如果匹配器与原始值组合,则可能发生此异常:     //不正确:     someMethod(anyObject(),“原始字符串”); 使用匹配器时,所有参数都必须由匹配器提供。 例如:     //正确:     someMethod(anyObject(),eq(“匹配者的字符串”));

1 个答案:

答案 0 :(得分:1)

问题在于您的dao不是嘲笑的对象,因此您不应该 通过匹配器。

错误:

dao.myDaoMethod(any(Date.class), any(Date.class));

正确:

dao.myDaoMethod(new Date(1), new Date(2));