【问题标题】:How to test Mongo indexes in integration tests?如何在集成测试中测试 Mongo 索引?
【发布时间】:2017-06-08 21:37:50
【问题描述】:

我有一个 Java 方法,它在 Mongo 集合的两个字段上创建索引。 我应该获取集合的索引信息,然后检查索引的名称和字段是否正确。 为此编写集成测试的最简洁方法是什么?使用自定义 Hamcrest 匹配器来查看索引是否在集合中是否有意义?

【问题讨论】:

    标签: java mongodb indexing integration-testing


    【解决方案1】:

    春天

    使用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 匹配器。

    【讨论】:

      猜你喜欢
      • 2014-10-17
      • 2022-08-10
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多