huangyuanmu 发表于 2013-1-29 07:31:37

javascript单元测试

为了保证javascript代码的质量,特别是javascript类库代码的质量,使用单元测试还是非常有必要的。java有junit单元测试框架,javascrip当然就有jsunit测试框架(其实是从junit移植过来的,用一下就知道了,令人懊恼的红条,令人振奋的绿条)。既然有很方便的单元测试工具,那么就用起来吧,步骤如下:
 
1.从http://sourceforge.net/projects/jsunit下载jsunit框架及其eclipse插件,或者下载下边的附件
 
2.解压下载的压缩包,框架解压到你喜欢的目录中,插件以你熟悉的插件安装方式进行安装
 
3.配置插件(两个配置项:Jsunit installation directory;Browser executables)
http://www.agoit.com/upload/picture/pic/46881/2de24fee-5f2d-313e-a353-7e22ece973c6.jpg
 
4.写单元测试代码(例如我要测试我写的基础类库tohot.commons.Utils),需要写一个html文件,例如:tohot.commons.UtilsTests.html
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>JsUnit Tests example</title><link rel="stylesheet" type="text/css" href="../css/jsUnitStyle.css" mce_href="../css/jsUnitStyle.css" /><script language="JavaScript" type="text/javascript" src="lib/jsUnitCore.js" mce_src="lib/jsUnitCore.js"></script><script language="JavaScript" type="text/javascript" src="tohot.commons.Utils.js" mce_src="tohot.commons.Utils.js"></script><script type="text/javascript">var util = tohot.commons.Utils;function testInteger() { assertTrue(util.trueOrFalse("881231",util.regInteger)); assertTrue(util.trueOrFalse("-881231",util.regInteger)); assertTrue(util.trueOrFalse("+881231",util.regInteger)); assertFalse(util.trueOrFalse("++881231",util.regInteger)); assertFalse(util.trueOrFalse("aa",util.regInteger)); assertFalse(util.trueOrFalse("0.881231",util.regInteger));}</script></head><body></body></html> 
5.执行单元测试
http://www.agoit.com/upload/picture/pic/46883/6553bda0-a837-3229-82cf-3267137880f1.jpg
 
6.执行结果
http://www.agoit.com/upload/picture/pic/46885/c85e55f8-180d-3165-887b-2a63c96933d9.jpg
 
绿条,我喜欢,嘿嘿。
页: [1]
查看完整版本: javascript单元测试