如何使用Mockito模拟复杂的查询条件

时间:2019-05-14 11:56:07

标签: java spring mockito criteria

我正在为数据访问层中的方法编写一个junit测试用例,如何使用Mockito存根/验证复杂查询?

检查了以下有关如何对复杂查询进行存根的链接: -https://howtodoinjava.com/hibernate/hibernate-criteria-queries-tutorial/ -https://github.com/MorphiaOrg/morphia/issues/933

没有一个与我的情况相符,并且文档对此也没说太多 https://static.javadoc.io/org.mockito/mockito-core/2.8.9/index.html?org/mockito/Mockito.html

实际代码:

public List<Content> getContentByParams(String entity, String channelId, String sectionId,
            Integer limit, String[] retrievedFields) {

    Query<Content> query = this.createQuery();

    if (StringUtils.isNotBlank(channelId) && StringUtils.isNotBlank(sectionId)) {


        query.and(query.criteria("name").equalIgnoreCase(entity),

        query.criteria("channel").equal(channelId),

        query.criteria("section").equal(sectionId));
            System.out.println("after===============");
    }
    if (retrievedFields != null && retrievedFields.length > 0) {
            System.out.println("retrieved fields");
            for (String field : retrievedFields) {
                query.project(field, true);
            }
        }

        if (limit == null) {
            limit = 4;
        }

        FindOptions findOptions = new FindOptions().limit(limit);

        return query.asList(findOptions);
}

测试用例:

public void getContentByEntitiesAndPrimaryChannelSection() {
        FieldEnd<Criteria> mockFieldEndEntity = mock(FieldEnd.class);
        FieldEnd<Criteria> mockFieldEndChannel = mock(FieldEnd.class);
        FieldEnd<Criteria> mockFieldEndSection = mock(FieldEnd.class);

        // doReturn(mockFieldEndEntity).when(query).criteria("name");
        // doReturn(mockFieldEndChannel).when(query).criteria("channel");
        // doReturn(mockFieldEndSection).when(query).criteria("section");

        contentDAO.getContentByParams(entity, "channel_3", "section_3", 10, mockFields);

        for (String field : mockFields) {
            verify(query).project(field, true);
        }


        ArgumentCaptor<FindOptions> argument = ArgumentCaptor.forClass(FindOptions.class);

        verify(query).asList(argument.capture());

        FindOptions findOptions = argument.getValue();
        assertEquals(10, findOptions.getLimit());

        PowerMockito.verifyStatic(MongoQueryUtil.class, times(1));
    }

我不确定如何通过其当前的测试状态为查询创建部件添加测试,但是它没有测试查询创建。 任何帮助将不胜感激,或者在某处有文档的帮助。

0 个答案:

没有答案