How to test Mongo indexes in integration tests?

后端 未结 1 522
无人共我
无人共我 2021-01-14 16:53

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

相关标签:
1条回答
  • 2021-01-14 17:51

    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.

    0 讨论(0)
提交回复
热议问题