I have a Java method which creates an index on two fields from a Mongo collection. I should get the index info for the collection, then check if the name and fields of the i
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.