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