如何在集成测试中测试Mongo索引?

时间:2017-06-08 21:37:50

标签: java mongodb indexing integration-testing

我有一个Java方法,它在Mongo集合的两个字段上创建索引。 我应该获取集合的索引信息,然后检查索引的名称和字段是否正确。 为此编写集成测试的最简洁方法是什么?使用自定义Hamcrest匹配器查看索引是否在集合中是否有意义?

1 个答案:

答案 0 :(得分:3)

在春天

使用MongoTemplate#indexOps(String collection),您可以获取IndexInfo的List,表示MongoDB集合的索引。由于这是一个常规列表,您可以使用hasItem(Matcher<? super T> itemMatcher)hasProperty(String propertyName, Matcher<?> valueMatcher)的组合来执行断言:

final List<IndexInfo> indexes = mongoTemplate.indexOps("myCollection").getIndexInfo();
assertThat(indexes, hasSize(3));
assertThat(indexes, hasItem(hasProperty("name", is("_id_"))));
assertThat(indexes, hasItem(hasProperty("name", is("index1"))));
assertThat(indexes, hasItem(hasProperty("name", is("index2"))));
assertThat(indexes, hasItem(hasProperty("indexFields", hasItem(hasProperty("key", is("field1"))))));

如果你发现这个太难以理解或者说不方便,那么使用自定义Hamcrest匹配器可能会更好。