Reputation: 5256
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 index are correct. What is the cleanest way to write an integration test for this? Would it make sense to use a custom Hamcrest matcher to see if the index is in the collection?
Upvotes: 3
Views: 1727
Reputation: 166
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.
Upvotes: 4