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

3

我有一个Java方法,可以在Mongo集合中为两个字段创建索引。我需要获取该集合的索引信息,然后检查索引的名称和字段是否正确。如何编写最干净的集成测试?使用自定义Hamcrest匹配器来检查索引是否在集合中是否有意义?

1个回答

3

在Spring中

使用MongoTemplate#indexOps(String collection),您可以获取代表MongoDB集合索引的IndexInfo列表。由于这是一个常规列表,因此您可以使用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匹配器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接