如何在不实际连接到mongo的情况下对连接到mongo的方法进行单元测试? [英] How to unit test a method which connects to mongo, without actually connecting to mongo?

查看:117
本文介绍了如何在不实际连接到mongo的情况下对连接到mongo的方法进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写测试来测试连接到mongo的方法,但我实际上并不想运行mongo并与其建立连接以使我的测试成功通过.

I'm trying to write a test to test a method that connects to mongo, but I don't actually want to have to have mongo running and actually make a connection to it to have my tests pass successfully.

这是我当前的测试,当我的mongo守护程序运行时,该测试成功.

Here's my current test which is successful when my mongo daemon is running.

describe('with a valid mongo string parameter', function() {
    it('should return a rejected promise', function(done) {
        var con = mongoFactory.getConnection('mongodb://localhost:27017');
        expect(con).to.be.fulfilled;
        done();
    });
});

mongoFactory.getConnection代码:

mongoFactory.getConnection code:

getConnection: function getConnection(connectionString) {

      // do stuff here

        // Initialize connection once
        MongoClient.connect(connectionString, function(err, database) {
          if (err) {
            def.reject(err);
          }

          def.resolve(database);
        });

      return def.promise;
    }

推荐答案

有一些与单元测试代码相关的SO答案,这些代码使用MongoDB作为数据存储:

There are a couple of SO answers related to unit testing code that uses MongoDB as a data store:

  • Mocking database in node.js?
  • Mock/Test Mongodb Database Node.js
  • Embedded MongoDB when running integration tests
  • Similar: Unit testing classes that have online functionality

我将尝试合并这些解决方案.

I'll make an attempt at consolidating these solutions.

首先,您应该希望MongoDB在执行测试时运行. MongoDB的查询语言很复杂,因此需要在稳定的MongoDB实例上运行合法查询,以确保您的查询按计划运行,并且您的应用程序能够正确响应结果.但是,考虑到这一点,您应该从不对生产系统运行测试,而应该对集成环境使用外围系统.它可以与CI软件位于同一台计算机上,也可以相对接近(就过程而言,不一定是网络或地理位置而言).

First and foremost, you should want MongoDB to be running while performing your tests. MongoDB's query language is complex, so running legitimate queries against a stable MongoDB instance is required to ensure your queries are running as planned and that your application is responding properly to the results. With this in mind, however, you should never run your tests against a production system, but instead a peripheral system to your integration environment. This can be on the same machine as your CI software, or simply relatively close to it (in terms of process, not necessarily network or geographically speaking).

此ENV可能占用空间较小,并且可以完全在内存中运行(资源1 )(资源2 ),但不一定需要与您的产品ENV具有相同的性能特征. (如果要进行性能测试,则无论如何都应在与CI不同的环境中进行处理.)

This ENV could be low-footprint and completely run in memory (resource 1) (resource 2), but would not necessarily require the same performance characteristics as your production ENV. (If you want to performance test, this should be handled in a separate environment from your CI anyway.)

  • 安装专门用于CI的mongod服务.如果需要考虑复制集和/或分片(例如,写入问题,不使用$isolated等),则可以通过在同一台计算机上运行多个mongod实例(1 config,shard + repl的2x2数据)和一个mongos实例来模拟集群环境,并执行一些init.d脚本/调整或类似docker的操作.
  • 在应用程序中使用特定于环境的配置(通过.json文件嵌入,或在/etc、/home/user/.your-app或类似位置)中进行.您的应用程序可以基于节点环境变量(如NODE_ENV=int )来加载它们.在这些配置中,您的数据库连接字符串将有所不同.如果您不是使用特定于env的配置,请开始执行此操作,以此作为抽象应用程序运行时设置(即本地","dev","int","pre","prod" , 等等.). 我可以应要求提供样品.
  • 在您的应用程序/测试套件中包括面向测试的装置.如链接的问题之一所述,MongoDB的Node.js驱动程序支持一些帮助程序库:
  • Install a mongod service specifically for CI. If repl sets and/or sharding are of concern (e.g. write concern, no use of $isolated, etc.), it is possible to mimic a clustered environment by running multiple mongod instances (1 config, 2x2 data for shard+repl) and a mongos instance on the same machine with either some init.d scripts/tweaks or something like docker.
  • Use environment-specific configurations within your application (either embedded via .json files, or in some place like /etc, /home/user/.your-app or similar). Your application can load these based on a node environment variable like NODE_ENV=int. Within these configurations your db connection strings will differ. If you're not using env-specific configs, start doing this as a means to abstract the application runtime settings (i.e. "local", "dev", "int", "pre", "prod", etc.). I can provide a sample upon request.
  • Include test-oriented fixtures with your application/testing suite. As mentioned in one of the linked questions, MongoDB's Node.js driver supports some helper libraries: mongodb-fixtures and node-database-cleaner. Fixtures provide a working and consistent data set for testing: think of them as a bootstrap.
  1. 使用类似node-database-cleaner的方法来清理关联的数据库.
  2. 借助mongodb-fixtures,将您的灯具放入现在为空的数据库中.
  3. 执行构建和测试.
  4. 重复.
  1. Clean the associated database using something like node-database-cleaner.
  2. Populate your fixtures into the now empty database with the help of mongodb-fixtures.
  3. Perform your build and test.
  4. Repeat.

另一方面...

如果您仍然认为运行MongoDB的 not 是正确的方法(,那么您将不是(最好只使用一个),然后使用ORM从驱动程序中提取数据存储调用是您最好的选择(对于整个应用程序,而不仅仅是测试).例如,虽然我从未使用过 model之类的东西,但它声称自己与数据库无关 .使用这种方法,您仍然需要夹具 env配置,但是不需要安装MongoDB.需要注意的是,您受制于所选择的ORM.

On the other hand...

If you still decide that not running MongoDB is the correct approach (and you wouldn't be the only one), then abstracting your data store calls from the driver with an ORM is your best bet (for the entire application, not just testing). For example, something like model claims to be database agnostic, although I've never used it. Utilizing this approach, you would still require fixtures and env configurations, however you would not be required to install MongoDB. The caveat here is that you're at the mercy of the ORM you choose.

这篇关于如何在不实际连接到mongo的情况下对连接到mongo的方法进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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