你如何在 Node.js 中模拟 MySQL(没有 ORM)?
我正在使用 Node.js
和 felixge 的 node-mysql
客户端.我没有使用 ORM.
I'm using Node.js
with felixge's node-mysql
client. I am not using an ORM.
我正在使用 Vows 进行测试,并希望能够模拟我的数据库,可能使用 Sinon.由于我本身并没有真正的 DAL(除了 node-mysql
),我不确定如何去做.我的模型大多是带有很多吸气剂的简单 CRUD.
I'm testing with Vows and want to be able to mock my database, possibly using Sinon. Since I don't really have a DAL per se (aside from node-mysql
), I'm not really sure how to go about this. My models are mostly simple CRUD with a lot of getters.
关于如何实现这一点的任何想法?
Any ideas on how to accomplish this?
推荐答案
使用 sinon,您可以在整个模块周围放置一个 mock 或 stub.例如,假设 mysql
模块有一个函数 query
:
With sinon, you can put a mock or stub around an entire module. For example, suppose the mysql
module has a function query
:
var mock;
mock = sinon.mock(require('mysql'))
mock.expects('query').with(queryString, queryParams).yields(null, rows);
queryString
、queryParams
是您期望的输入.rows
是您期望的输出.
queryString
, queryParams
are the input you expect. rows
is the output you expect.
当你的被测类现在需要mysql并调用query
方法时,会被sinon拦截验证.
When your class under test now require mysql and calls the query
method, it will be intercepted and verified by sinon.
在你的测试期望部分你应该有:
In your test expectation section you should have:
mock.verify()
在您的拆解过程中,您应该将 mysql 恢复到正常功能:
and in your teardown you should restore mysql back to normal functionality:
mock.restore()
相关文章