从testing中解耦查询的最佳实践

我正在寻找使用mocha或sinontestingmysql查询的最佳实践。 我试图testing非常基本的数据库查询,如保存:

User.prototype.save = function(cb) { var query = 'INSERT INTO user (name, email, password, img, description)' + 'values (?, ?, ?, ?, ?)'; var params = [this.name, this.email, this.pass, this.img, this.description]; db.query(query, params, function(err, rows) { if (err) return cb(err); cb(rows.insertId); } ); }; 

我相信我想做一个模拟数据库,并使用该对象,而不是我的数据库对象,但我也想分开testing逻辑从应用程序逻辑。

我尝试了一些变化

 describe('User', function() { before(function() { mock = sinon.mock(require('../middleware/db')); }) describe('.save()', function() { var uid; it('should run save on a user', function() { var user = new User ({ name: 'Test Case 1', email: 't1@example.com', pass: 'pass', img: 'path/to/img.jpg' }); user.save(function(id) { id.should.be.ok; var uid = id; }); }) it('should save the user', function() { var ret = User.find(uid); ret.should.be.ok; ret.should.have.property('description'); ret.name.should.equal('Test Case 1'); ret.email.should.equal('t1@example.com'); }) }) 

什么是testing这种types的function的最佳做法?

谢谢

与数据库的实际交互不应该由unit testing来处理,而应该通过端到端testing来处理。 使用数据库进行端到端testing的最佳做法是定义数据库状态,在每次testing之前将数据库状态加载到数据库中。

在unit testing方面,因为这个方法是调用外部模块的包装,所以将unit testing推迟到第三方可能就足够了。