读书人

Clojure-JVM下的函数式编程语言(13)自

发布时间: 2012-10-06 17:34:01 作者: rapoo

Clojure-JVM上的函数式编程语言(13)自动化测试 作者: R. Mark Volkmann

?原帖地址:http://java.ociweb.com/mark/clojure/article.html#Testing

?作者:R. Mark Volkmann

?译者:RoySong

?

自动化测试

??? Clojure基本的自动化测试框架就在Clojure核心代码的测试库中。下面的代码展示了它的主要功能:

(use 'clojure.test); Tests can be written in separate functions.(deftest add-test  ; The "is" macro takes a predicate, arguments to it,  ; and an optional message.  (is (= 4 (+ 2 2)))  (is (= 2 (+ 2 0)) "adding zero doesn't change value"))(deftest reverse-test  (is (= [3 2 1] (reverse [1 2 3])))); Tests can verify that a specific exception is thrown.(deftest division-test  (is (thrown? ArithmeticException (/ 3.0 0)))); The with-test macro can be used to add tests; to the functions they test as metadata.(with-test  (defn my-add [n1 n2] (+ n1 n2))  (is (= 4 (my-add 2 2)))  (is (= 2 (my-add 2 0)) "adding zero doesn't change value")); The "are" macro takes a predicate template and; multiple sets of arguments to it, but no message.; Each set of arguments are substituted one at a time; into the predicate template and evaluated.(deftest multiplication  (are [n1 n2 result]    (= (* n1 n2) result) ; a template    1 1 1,    1 2 2,    2 3 6)); Run all the tests in the current namespace.; This includes tests that were added as function metadata using with-test.; Other namespaces can be specified as quoted arguments.(run-tests)
?

??? 为了限制当一个测试抛出异常时输出堆栈的深度,绑定特殊符号*stack-trace-depth*一个深度值。

?

??? 在为了产品使用,采用AOT编译Clojure源码为字节码时,绑定*load-tests*符号为false来避免测试代码被编译成

字节码。

?

??? 当不出与自动化测试这一层时,Clojure提供了assert宏。它接收一个表达式并对其求值,如果求值的结果是false,

则抛出一个异常。这对于捕获绝对不应该发生的情况非常有用。例子如下:

(assert (>= dow 7000))
?

??? 测试库的另一个重要特性是装置(fixtures),装置是环绕着测试方法的代码。装置有两类,一类是环绕每个测试方法

的执行,而另一类是环绕所有测试方法的执行。

?

??? 为了创建一个装置,编写一个函数采用以下模式:

(defn fixture-name [test-function]  ; Perform setup here.  (test-function)  ; Perform teardown here.)
?

??? 这样针对每个测试函数都会调用一次装置函数,test-function参数的值将是当前执行的函数。

?

??? 注册装置来环绕每个测试方法:

(use-fixtures :each fixture-1 fixture-2 ...)
?

??? 执行的顺序将是:

    fixture-1初始化fixture-2初始化一个测试函数fixture-2卸载fixture-1卸载

??? 注册装置来环绕整体测试运行:

(use-fixtures :once fixture-1 fixture-2 ...)
?

??? 执行的顺序将是:

    fixture-1初始化fixture-2初始化所有测试函数fixture-2卸载fixture-1卸载

??? Clojure在test子目录下装有自身的测试套件,切换到包含有Clojure src和test的目录下,然后键入"ant test"

就可以运行它们。

读书人网 >编程

热点推荐