Clojure:如何在测试中使用灯具

Dav*_*ams 12 unit-testing clojure

我正在编写一些与数据库交互的单元测试.因此,在单元测试中使用设置和拆卸方法来创建然后删除表是很有用的.但是在use-fixtures方法上没有文档:O.

这是我需要做的:

 (setup-tests)
 (run-tests)
 (teardown-tests)
Run Code Online (Sandbox Code Playgroud)

目前我对在每次测试之前和之后运行设置和拆卸感兴趣,但是在一组测试之前和之后一次.你怎么做到这一点?

Joo*_*aat 22

您不能使用use-fixtures为自由定义的测试组提供设置和拆卸代码,但您可以使用:once它为每个命名空间提供设置和拆卸代码:

;; my/test/config.clj
(ns my.test.config)

(defn wrap-setup
  [f]
  (println "wrapping setup")
  ;; note that you generally want to run teardown-tests in a try ...
  ;; finally construct, but this is just an example
  (setup-test)
  (f)
  (teardown-test))    


;; my/package_test.clj
(ns my.package-test
  (:use clojure.test
        my.test.config))

(use-fixtures :once wrap-setup) ; wrap-setup around the whole namespace of tests. 
                                ; use :each to wrap around each individual test 
                                ; in this package.

(testing ... )
Run Code Online (Sandbox Code Playgroud)

这种方法迫使设置和拆卸代码与测试所在的软件包之间存在一些耦合,但通常这不是一个大问题.您可以随时进行自己的手动换行,testing例如参见本博文的下半部分.