使用,MongoTemplate#indexOps(String collection)
您可以获取的列表IndexInfo
,代表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匹配器。