如何在Spring JdbcTemplate中模拟数据源

时间:2017-03-08 06:33:22

标签: unit-testing junit mockito powermockito spring-junit

请帮我模拟下面的代码。无法模拟调用JdbcTemplate对象的getDataSource()。

@Override
public List<AttributeThresholdRange> getThresholdsRangeForXHS(QueryThresholdsRequest queryThresholdsRequest) {

    ArrayOfString attributeGroupIds = queryThresholdsRequest.getAttributeGroupIds();
    Map<String, Object> queryParams = new HashMap<>();
    queryParams.put("groupids", attributeGroupIds.getStrings());

    return new NamedParameterJdbcTemplate(admDatabaseConnector.getJdbcTemplate().getDataSource())
            .query(DBQueryConstants.ADM_QUERY_GET_THRESHOLDS_RANGE_FOR_XHS, 
                    queryParams,
                    new ResultSetExtractor<List<AttributeThresholdRange>>() {
                @Override
                public List<AttributeThresholdRange> extractData(ResultSet resultSet) throws SQLException,DataAccessException  {

                    return null;
                }
            });
}

1 个答案:

答案 0 :(得分:1)

你正在使用Mock框架吗?

如果你正在使用Mockito,只需模拟select t1.name, t2.roleid, t3.department, t4.country from dbo.user t1 inner join dbo.role t2 on t1.roleid = t2.roleid inner join dbo.tbldepartment t3 on t1.departmentid= t3.departmentid inner join dbo.country t4 on t1.countryid = t4.countryid 并将此方法放在jdbcTemplate子句中。

when()

您必须在模拟中声明when(admDatabaseConnector.getJdbcTemplate().getDataSource()) .query(anyObject(), anyObject(), anyObject())).thenReturn("Your return queryobject");