Unit testing Clojure:如何在测试中使用夹具
我正在编写一些与数据库交互的单元测试。因此,在我的单元测试中使用setup和teardown方法来创建并删除表是很有用的。但是:O使用fixtures方法 以下是我需要做的:Unit testing Clojure:如何在测试中使用夹具,unit-testing,clojure,Unit Testing,Clojure,我正在编写一些与数据库交互的单元测试。因此,在我的单元测试中使用setup和teardown方法来创建并删除表是很有用的。但是:O使用fixtures方法 以下是我需要做的: (setup-tests) (run-tests) (teardown-tests) 我目前对在每个测试之前和之后运行安装和拆卸不感兴趣,而是在一组测试之前和之后运行一次。如何做到这一点?您不能使用使用fixture为自由定义的测试组提供设置和拆卸代码,但可以使用:once为每个命名空间提供设置和拆卸代码: ;;
(setup-tests)
(run-tests)
(teardown-tests)
我目前对在每个测试之前和之后运行安装和拆卸不感兴趣,而是在一组测试之前和之后运行一次。如何做到这一点?您不能使用
使用fixture
为自由定义的测试组提供设置和拆卸代码,但可以使用: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 ... )
这种方法在安装和拆卸代码以及测试所在的包之间强制进行一些耦合,但通常这不是一个大问题。您可以在测试
部分中自行手动包装,例如参见。按照:
fixture允许您在测试前后运行代码,以设置
应该在其中运行测试的上下文
fixture只是一个函数,它调用另一个作为
论点看起来是这样的:
(defn my-fixture [f]
;; Perform setup, establish bindings, whatever.
(f) ;; Then call the function we were passed.
;; Tear-down / clean-up code here.
)
(use-fixtures :once fixture1 fixture2 ...)
在单独的测试周围有“每个”装置用于设置和拆卸,但您写道您想要“一次”装置提供的:
[A] “一次”夹具仅运行一次
命名空间中的所有测试。“一次性”装置对于任务很有用
这只需要执行一次,就像建立数据库一样
连接,或用于耗时的任务
将“一次”装置附加到当前名称空间,如下所示:
(defn my-fixture [f]
;; Perform setup, establish bindings, whatever.
(f) ;; Then call the function we were passed.
;; Tear-down / clean-up code here.
)
(use-fixtures :once fixture1 fixture2 ...)
我可能会写下你的固定装置,比如:
(use-fixtures :once (fn [f]
(setup-tests)
(f)
(teardown-tests)))
谢谢,我最终使用了这样的东西:
(defn test ns hook[](创建表)(put-4)(put-5)(get-2)(get-3)(get-4)(scan-2)(scan-3)(scan-4)(drop-table))
@DavidWilliams你不应该真的把你的测试放在wrap/hook中。fixture的全部要点是将设置代码与测试分开。这就是钩子的参数(在我的例子中是f)的作用;它是一个回调函数,在fixture代码的正确位置运行测试(和任何其他挂钩)。然后像往常一样定义测试(例如使用deftest)。很高兴看到现在链接的URL上有很多文档:)和