2011-04-11
nodeunitを使ったテストコード
サーバーにnodeを使いつつTDDをするためにnodeunitを使ってみた。試しにmongoDBの操作を直列で記述できるラッパーを作って、それのテストケースを3つ書いた。
テストコード
var mongodb = require('mongodb'); var Transaction = require('./mongotransaction').MongoTransaction; var db, case1 = {}; case1.setUp = function(next) { var server = new mongodb.Server("127.0.0.1", 27017, {}); db = new mongodb.Db('test', server, {}); next(); } case1["Open and close DB"] = function(test) { new Transaction(db) .exec(function(next) { test.equal(this.db.state, "notConnected"); next(); }) .openDB() .exec(function(next, client) { test.equal(this.db.state, "connected"); next(client); }) .closeDB() .exec(function(next, client) { test.equal(this.db.state, "notConnected"); test.done(); }) .start(); }; case1["Insert document"] = function(test) { var colName = 'unitTest'; new Transaction(db) .openDB() .removeAll(colName) .insert(colName, {name: 'Insert test'}) .find(colName, {}, {}) .openCursor('toArray') .exec(function(next, cx) { test.equal(cx.arr.length, 1); test.equal(cx.arr[0].name, 'Insert test'); test.done(); next(cx.db); }) .closeDB() .start(); } case1["Handle Exception and close DB"] = function(test) { var colName = 'unitTest'; new Transaction(db) .openDB() .removeAll(colName) .find(colName, {}, {}) .openCursor('toArray') .exec(function(next, cx) { // Throws exception (cx.arr[10] is undefined) cx.arr[10].toString(); test.ok(false, "This line shoud not be called"); }) .onFailure(function(e) { test.equal(this.db.state, 'notConnected'); test.ok(true, "handle failure succeeded"); test.done(); }) .start(); } module.exports = require('nodeunit').testCase(case1);
実行結果
いいですね。QUnitよりも非同期処理のテストがスマートに書ける。
簡単な使い方は次のエントリがわかりやすい
TDD: async testing with nodeunit
http://node-js.ru/7-tdd-async-nodeunit-tests
高度な使い方はGithubリポジトリのreadmeに詳しく書いてある
caolan/nodeunit - GitHub
https://github.com/caolan/nodeunit
トラックバック - http://d.hatena.ne.jp/hagino_3000/20110411/nodeunit
リンク元
- 11 http://twitter.com/
- 7 http://reader.livedoor.com/reader/
- 6 http://ezsch.ezweb.ne.jp/search/?sr=0101&query=kinect shibuya
- 6 http://www.google.co.jp/search?hl=ja&lr=lang_ja&tbs=lr:lang_1ja&q=WebGL+opengl&aq=f&aqi=g1&aql=&oq=
- 4 http://www.google.co.jp/search?q=google+account+openid+hybrid&hl=ja&safe=active&client=firefox-a&hs=Q6V&rls=org.mozilla:ja:official&prmd=ivns&source=lnt&tbs=lr:lang_1ja&lr=lang_ja&sa=X&ei=LtWjTZ6eDoTGvQPF6eyNCg&ved=0CAcQpwUoAQ
- 3 http://b.hatena.ne.jp/entrylist?sort=hot&threshold=5
- 3 http://node-js.info/?p=226
- 3 http://www.google.co.jp/search?hl=ja&rlz=1T4ADRA_jaJP407JP425&sa=X&ei=IhOkTa7MK4ncvwPyoNiYCg&ved=0CBcQBSgA&q=anywhere+twitter+seasar2&spell=1
- 2 http://ezsch.ezweb.ne.jp/search/?query=エロ動画サイト&start-index=16&adpage=4&ct=1101&sr=0101&t=20110414112114&filter=1
- 2 http://ezsch.ezweb.ne.jp/search/?query=+KINECT+ハックの仕方&start-index=11&adpage=3&ct=1301&sr=0000&t=20110412123101&filter=1




