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

查看:338
本文介绍了在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 ?

当然,我可以将数据库设置为特定的测试数据库,但我仍然保存数据,而不是测试我的代码,但也是数据库,所以我实际上不做单元测试,但集成测试。

那么应该怎么办?创建数据库包装器作为应用程序和数据库之间的中间层,并在测试时替换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 vs Firefox vs 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天全站免登陆