在 node.js 中模拟数据库? [英] Mocking database in node.js?

查看:45
本文介绍了在 node.js 中模拟数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在我的 node.js 应用程序中模拟数据库,在本例中使用 mongodb 作为博客 REST API 的后端?

How would I mock out the database in my node.js application, which in this case uses mongodb as the backend for a blog REST API ?

当然,我可以将数据库设置为特定的 testing -database,但我仍然会保存数据,不仅测试我的代码,还测试数据库,所以我实际上没有进行单元测试但集成测试.
那么应该怎么做呢?创建数据库包装器作为应用程序和数据库之间的中间层并在测试时替换 DAL?

Sure, I could set the database to a specific testing -database, but I would still save data and not test my code only, but also the database, so I am actually not doing unit testing but integration testing.
So what should one do? Create database wrappers as a middle layer between application and db and replace the DAL when in testing?

// app.js  
var express = require('express');
    app = express(),
    mongo = require('mongoskin'),
    db = mongo.db('localhost:27017/test?auto_reconnect');

app.get('/posts/:slug', function(req, res){
    db.collection('posts').findOne({slug: req.params.slug}, function (err, post) {
        res.send(JSON.stringify(post), 200);
    });
});

app.listen(3000);

<小时>

// test.js
r = require('requestah')(3000);
describe("Does some testing", function() {

  it("Fetches a blogpost by slug", function(done) {
    r.get("/posts/aslug", function(res) {
      expect(res.statusCode).to.equal(200);
      expect(JSON.parse(res.body)["title"]).to.not.equal(null);
      return done();
    });

  });
));

推荐答案

我认为如果不使用数据库软件进行测试,就无法正确测试与数据库相关的代码.那是因为您正在测试的代码不仅是 javascript,还包括数据库查询字符串.即使在您的情况下,查询看起来很简单,但您不能永远依赖它.

I don't think database related code can be properly tested without testing it with the database software. That's because the code you're testing is not just javascript but also the database query string. Even though in your case the queries look simple you can't rely on it being that way forever.

因此任何数据库仿真层都必须实现整个数据库(可能减去磁盘存储).到那时,您最终会使用数据库模拟器进行集成测试,即使您将其称为单元测试.另一个缺点是,与数据库相比,数据库模拟器最终可能会出现一组不同的错误,您可能最终不得不为数据库模拟器和数据库编写代码(有点像 IE 与 Firefox 与 Chrome 等的情况.).

So any database emulation layer will necessarily implement the entire database (minus disk storage perhaps). By then you end up doing integration testing with the database emulator even though you call it unit testing. Another downside is that the database emulator may end up having a different set of bugs compared to the database and you may end up having to code for both the database emulator and the database (kind of like the situation with IE vs Firefox vs Chrome etc.).

因此,在我看来,正确测试代码的唯一方法是将其与真实数据库连接.

Therefore, in my opinion, the only way to correctly test your code is to interface it with the real database.

这篇关于在 node.js 中模拟数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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