使用NoSQLUnit测试Spring Data MongoDB应用程序

Spring Data MongoDBSpring Data项目中的项目,它提供了Spring编程模型的扩展,用于编写使用MongoDB作为数据库的应用程序。

要使用NoSQLUnitSpring Data MongoDB应用程序编写测试,除了考虑Spring Data MongoDB使用一个名为_class的特殊属性来将类型信息存储在文档中之外,您不需要做任何其他事情。

_class属性将顶级文档以及复杂类型中的每个值的标准类名存储在文档中。

类型映射

MappingMongoConverter用作默认类型映射实现,但您可以使用@TypeAlias或实现TypeInformationMapper接口自定义更多类型。

应用

Starfleet已要求我们开发一个应用程序,用于将所有星际飞船乘员的日志存储到他们的系统中。 为了实现此要求,我们将在持久层使用MongoDB数据库作为后端系统,并使用Spring Data MongoDB
日志文档具有下一个json格式:

日志文件示例
{
        "_class" : "com.lordofthejars.nosqlunit.springdata.mongodb.log.Log" ,
        "_id" : 1 ,
        "owner" : "Captain" ,
        "stardate" : {
                "century" : 4 ,
                "season" : 3 ,
                "sequence" : 125 ,
                "day" : 8
        } ,
        "messages" : [
                        "We have entered a spectacular binary star system in the Kavis Alpha sector on a most critical mission of astrophysical research. Our eminent guest, Dr. Paul Stubbs, will attempt to study the decay of neutronium expelled at relativistic speeds from a massive stellar explosion which will occur here in a matter of hours." ,
                        "Our computer core has clearly been tampered with and yet there is no sign of a breach of security on board. We have engines back and will attempt to complete our mission. But without a reliable computer, Dr. Stubbs' experiment is in serious jeopardy."
        ]
}

该文档被建模为两个Java类,一个用于整个文档,另一个用于stardate部分。

星际约会
@Document
public class Stardate {

        private int century;
        private int season;
        private int sequence;
        private int day;

        public static final Stardate createStardate(int century, int season, int sequence, int day) {

                Stardate stardate = new Stardate();

                stardate.setCentury(century);
                stardate.setSeason(season);
                stardate.setSequence(sequence);
                stardate.setDay(day);

                return stardate;

        }

        //Getters and Setters
}
日志类别
@Document
public class Log {

        @Id
        private int logId;

        private String owner;
        private Stardate stardate;

        private List<String> messages = new ArrayList<String>();

        //Getters and Setters
}

除了模型类,我们还需要DAO类来实现CRUD操作和spring应用程序上下文文件。

MongoLogManager类
@Repository
public class MongoLogManager implements LogManager {

        private MongoTemplate mongoTemplate;

        public void create(Log log) {
                this.mongoTemplate.insert(log);
        }

        public List<Log> findAll() {
                return this.mongoTemplate.findAll(Log.class);
        }

        @Autowired
        public void setMongoTemplate(MongoTemplate mongoTemplate) {
                this.mongoTemplate = mongoTemplate;
        }

}
应用程序上下文文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.1.xsd">

     <context:component-scan base-package="com.lordofthejars.nosqlunit.springdata.mongodb"/>
     <context:annotation-config/>

</beans>

对于此示例,我们使用MongoTemplate类访问MongoDB来创建一个不复杂的示例,但是在更大的项目中,我建议通过在管理器类上实现CrudRepository接口来使用Spring Data Repository方法。

测试中

如前所述,除了正确使用class属性之外,您无需执行任何其他特殊操作。 让我们看看通过为日志数据库播种_log集合来测试findAll方法的数据集。

所有日志文件
{
        "log":[
                {
                        "_class" : "com.lordofthejars.nosqlunit.springdata.mongodb.log.Log" ,
                        "_id" : 1 ,
                        "owner" : "Captain" ,
                        "stardate" : {
                                "century" : 4 ,
                                "season" : 3 ,
                                "sequence" : 125 ,
                                "day" : 8
                        } ,
                        "messages" : [
                                "We have entered a spectacular binary star system in the Kavis Alpha sector on a most critical mission of astrophysical research. Our eminent guest, Dr. Paul Stubbs, will attempt to study the decay of neutronium expelled at relativistic speeds from a massive stellar explosion which will occur here in a matter of hours." ,
                                "Our computer core has clearly been tampered with and yet there is no sign of a breach of security on board. We have engines back and will attempt to complete our mission. But without a reliable computer, Dr. Stubbs' experiment is in serious jeopardy."
                        ]
                }
                ,
                {
                        "_class" : "com.lordofthejars.nosqlunit.springdata.mongodb.log.Log" ,
                        "_id" : 2 ,
                        "owner" : "Captain" ,
                        "stardate" : {
                                "century" : 4 ,
                                "season" : 3 ,
                                "sequence" : 152 ,
                                "day" : 4
                        } ,
                        "messages" : [
                                "We are cautiously entering the Delta Rana star system three days after receiving a distress call from the Federation colony on its fourth planet. The garbled transmission reported the colony under attack from an unidentified spacecraft. Our mission is one of rescue and, if necessary, confrontation with a hostile force."
                        ]
                }
                ...
}

看到_class属性设置为Log类的全限定名。

下一步是配置MongoTemplate以执行测试。

LocalhostMongoAppConfig
@Configuration
@Profile("test")
public class LocalhostMongoAppConfig {

        private static final String DATABASE_NAME = "logs";

        public @Bean Mongo mongo() throws UnknownHostException, MongoException {
                Mongo mongo = new Mongo("localhost");
                return mongo;
        }

        public @Bean MongoTemplate mongoTemplate() throws UnknownHostException, MongoException {
                MongoTemplate mongoTemplate = new MongoTemplate(mongo(), DATABASE_NAME);
                return mongoTemplate;
        }

}

注意,仅当测试配置文件处于活动状态时,此MongoTemplate对象才会实例化。

现在我们可以编写JUnit测试用例:

当海军上将想要阅读日志时
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:com/lordofthejars/nosqlunit/springdata/mongodb/log/application-context-test.xml")
@ActiveProfiles("test")
@UsingDataSet(locations = "all-logs.json", loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
public class WhenAlmiralWantsToReadLogs {

        @ClassRule
        public static ManagedMongoDb managedMongoDb = newManagedMongoDbRule()
                        .mongodPath(
                                        "/Users/alexsotobueno/Applications/mongodb-osx-x86_64-2.0.5")
                        .build();

        @Rule
        public MongoDbRule mongoDbRule = newMongoDbRule().defaultManagedMongoDb("logs");

        @Autowired
        private LogManager logManager;

        @Test
        public void all_entries_should_be_loaded() {

                List<Log> allLogs = logManager.findAll();
                assertThat(allLogs, hasSize(3));

        }

}

在上一课中有一些要点要看:

  1. 由于NoSQLUnit使用JUnit规则,因此您可以自由使用@RunWith(SpringJUnit4ClassRunner)
  2. 使用@ActiveProfiles我们正在加载测试配置而不是生产配置。
  3. 您可以毫无问题地使用@Autowired 类的Spring注释。

结论

为无Spring Data MongoDB编写测试和使用它的应用程序之间没有太大区别。 仅记住正确定义_class属性。

参考:One Jar To Rule All All博客中,我们的JCG合作伙伴 Alex Soto 使用NoSQLUnit测试了Spring Data MongoDB应用程序

翻译自: https://www.javacodegeeks.com/2013/01/testing-spring-data-mongodb-applications-with-nosqlunit.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值