How to test Mongo indexes in integration tests?

假如想象 提交于 2020-05-23 17:51:54

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44445986/how-to-test-mongo-indexes-in-integration-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!