在 node.js 中模拟数据库?

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

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

发布评论

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

>www.elefans.com

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