什么是单元测试?
单元测试又称为模块测试,是针对程序模块(软件设计的最小单位)来进行正确性检验的测试工作。单元测试主要是用来检验程式的内部逻辑,也称为个体测试、结构测试或逻辑驱动测试。通常由撰写程式码的程式设计师负责进行。
通常来说,程式設計師每修改一次程式就會進行最少一次單元測試,在編寫程式的過程中前後很可能要進行多次單元測試,以證實程式達到軟件規格書(en:Specification)要求的工作目標,沒有臭蟲;雖然单元测试不是什么必须的,但也不坏,這牽涉到專案管理的政策決定。
单元测试的优点
1、它是一种验证行为。
程序中的每一项功能都是测试来验证它的正确性。它为以后的开发提供支缓。就算是开发后期,我们也可以轻松的增加功能或更改程序结构,而不用担心这个过程中会破坏重要的东西。而且它为代码的重构提供了保障。这样,我们就可以更自由的对程序进行改进。
2、它是一种设计行为。
编写单元测试将使我们从调用者观察、思考。特别是先写测试(test-first),迫使我们把程序设计成易于调用和可测试的,即迫使我们解除软件中的耦合。
3、它是一种编写文档的行为。
单元测试是一种无价的文档,它是展示函数或类如何使用的最佳文档。这份文档是可编译、可运行的,并且它保持最新,永远与代码同步。
4、它具有回归性。
自动化的单元测试避免了代码出现回归,编写完成之后,可以随时随地的快速运行测试。
参考:
http://miiceic.org.cn/phrase/200602281036115.html
http://tech.ddvip.com/2009-06/1245992965124860.html
http://www.blogjava.net/square/articles/158103.html
javscript中单元测试框架
简单说来,FireUnit给Firebug增加了一个标签面板,并提供了一些简单的JavaScript API来记录和查看测试。更多http://shawphy.com/2008/12/fireunit.html。
评价:里面有Test.Simple的痕迹,呵呵,John Resig是个非常善于学习并创新的家伙。FireUnit果然在易用性上表现非常出众,非常适合基于Firebug做调试环境的前端工程师。
Evaluation: Easy to use and beautiful interface.
Reference:
http://www.cnblogs.com/kaima/archive/2009/04/09/javascritp_unittest.html
Let’s focus on introducing QUnit
QUnit Introduction
JavaScript still needs good readability, so refactoring is also essential. We know that refactoring without unit tests is unreliable. Good unit test coverage will make it easier and more cost-effective for us to refactor. It is also lower, so a unit testing framework is very much needed for excellent JavaScript programmers. QUnit is a powerful and easy-to-use JavaScript testing framework. It is used for testing jQuery and its plug-ins. It can also test ordinary JavaScript code.
Using QUnit
First we need to find qunit.js and in http://docs.jquery.com/QUnit >qunit.cssTwo files, the framework of Qunit is as follows:
test( name, expected, test ): Add a test to run, which can contain several assertion functions, for example ok, equals, etc.
ok( state, [message] ) is a commonly used judgment function in QUnit. It can judge Boolean type. Non-zero integer is true. If the string is not "", it is true.
equals( actual, expected, [message] ) is a commonly used equality function in QUnit
Let’s look at a slightly more complicated one Example:
module( name, lifecycle ): is used to group test modules, [lifecycle] is used to initialize tests and cleanup tests.
Refer to the following example:
"/Home/JosnDemo" is the address that provides json data. It should be noted here that the start() function must be called after writing the assertion function.
Qunit also provides some more advanced applications during testing. For example, if you want to do some work at the beginning of a certain test, please see http://docs.jquery.com/QUnit #Integration_into_Browser_Automation_Tools
Many core suites of JQuery are tested using Qunit. http://docs.jquery.com/QUnit#Reference_Test_SuitesThere are many examples for your reference .
Example download