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

How to test Mongo indexes in integration tests?

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

In Spring

With MongoTemplate#indexOps(String collection) you can fetch a List of IndexInfo, representing the indexes of the MongoDB collection. Since this is a regular list you could do your assertions with a combination of hasItem(Matcher<? super T> itemMatcher) and 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"))))));

If you find this too unreadable or unhandy you might be better off with a custom Hamcrest matcher.