在node.js中模拟数据库?

编程入门 行业动态 更新时间:2024-10-26 12:26:00
本文介绍了在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中模拟数据库?

本文发布于:2023-10-19 00:02:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1505815.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库   node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!