不知道有多少人会写js的unit test, 不过最近的项目对unittest要求比较严格.所以也养成了写unittest的习惯. 在搞js-shell时, 对写的代码没有做test,总是不放心. 找了一些资料看到JQuery的unit test方法不错. 学习了一下也在js-shell加入了Uinttest库. 总算把前面的代码都加上了UT才放心.
js-shell中的unittest的使用方法和概念都和junit差不多, 主要有TestRunner, TestResult, TestSuite, TestCaseContext几个对象. 下面是一个例子:
1. 先实现一个test runner, 创建run_unit_test.js 这是必须的步骤,不过内容很简单:
var ut = __import__('UnitTest', null, {}) //导入Unitest 库
ut.run_suite('.') //运行Testsuite, 将运行当前目录下的所有以'test_'开头的js文件作为unittest运行.
2. 实现一个unitest, 创建test_hellotest.js
test("assertEqual", function() { //一个unittest, 名称为"assertEqual", function为 test的内容. assertEqual(10+ 20, 30) //一个比较断言,, }); test("assertEqual fail no message", function() { //一个失败的 unitest 例子. assertEqual(10+ 20, 31) }); test("assertEqual fail with message", function() { assertEqual(10+ 20, 31, "10+20 != 31") }); test("assertRaises expect raised", function() { //测试一个将要抛出异常的方法. assertRaises('Stop', function(m){throw m}, 'Stop') }); test("assertRaises mismatch raised", function() { assertRaises('Stop', function(m){throw m}, 'Start') }); test({ //实现一个Unittest对象, 包含setUp, tearDown. setUp: function(){ //一个setUp, 在每个test方法调用之前调用. this.msg = "enter setUp"; info('enter setUp'); //在Test中输出消息. }, test_basic_requirements: function(){ //一个方法内的test, 方法名必须以"test_"开头 info('running test_basic_requirements'); assertEqual(this.msg, "enter setUp") this.msg = 'test_basic_requirements' }, test_setUp_called_for_every_functional: function(){ info('test_setUp_called_for_every_functional'); assertEqual(this.msg, "enter setUp") this.msg = 'test_setUp_called_for_every_functional' }, tearDown: function(){ //在每个test调用用调用. this.msg = "enter tearDown"; info('enter tearDown'); }, });
3. 运行unit test
C:\utest>js run_unit_test.js
[INFO]:Start test file:C:\utest\test_hellotest.js
assertEqual...PASS in 0ms
assertEqual fail no message...FAIL in 16ms
expected: 31, actual: 30
assertEqual fail with message...FAIL in 0ms
10+20 != 31
assertRaises expect raised...PASS in 0ms
assertRaises mismatch raised...FAIL in 0ms
expected exception:Stop, catched:Start
[INFO]test_setUp_called_for_every_functional:enter setUp
[INFO]test_setUp_called_for_every_functional:test_setUp_called_for_every_functio
nal
[INFO]test_setUp_called_for_every_functional:enter tearDown
test_setUp_called_for_every_functional...PASS in 31ms
[INFO]test_basic_requirements:enter setUp
[INFO]test_basic_requirements:running test_basic_requirements
[INFO]test_basic_requirements:enter tearDown
test_basic_requirements...PASS in 16ms
-----------------------------------------------------------
Ran 7 tests in 63ms
FAILED! Pass:4, Failed:3
这是一个简单的Unit, test. 测试的输出和UnitTest中的断言方法都可以自定义. 下次将介绍如何定义assert方法.