如何在集成测试中测试Mongo索引? [英] How to test Mongo indexes in integration tests?

查看:65
本文介绍了如何在集成测试中测试Mongo索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

在春季

使用MongoTemplate#indexOps(String collection),您可以获取IndexInfo的列表,该列表表示MongoDB集合的索引.由于这是一个常规列表,因此可以结合使用hasItem(Matcher<? super T> itemMatcher)hasProperty(String propertyName, Matcher<?> valueMatcher)进行断言:

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"))))));

如果您觉得这太难以理解或不方便使用,最好使用自定义的Hamcrest匹配器.

If you find this too unreadable or unhandy you might be better off with a custom Hamcrest matcher.

这篇关于如何在集成测试中测试Mongo索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆