一種方法是利用這樣的事實優勢,即使:once
將燈具無論是否有考試在納秒運行或不運行時,:each
燈具只會在每次實際運行的測試中運行。
而不是做實際的計算(或獲取資源,比如一個數據庫連接,或做任何副作用)在:once
固定的,我們只是做第一個(我們想這樣做只有一次!):each
夾具,例如做如下:
(def run-fixture? (atom true))
(defn enable-fixture [f]
(println "enabling expensive fixture...")
(try
(f)
(finally (reset! run-fixture? true))))
(defn expensive-fixture [f]
(if @run-fixture?
(do
(println "doing expensive computation and acquiring resources...")
(reset! run-fixture? false))
(println "yay, expensive thing is done!"))
(f))
(use-fixtures :once enable-fixture)
(use-fixtures :each expensive-fixture)
(deftest ^:integration integration-test
(println "first integration test"))
(deftest ^:integration second-integration-test
(println "second integration test"))
的lein test
輸出將是如下(請注意如何enable-fixture
已經運行,但不昂貴的expensive-fixture
):
› lein test
lein test fixture.core-test
enabling expensive fixture...
Ran 0 tests containing 0 assertions.
0 failures, 0 errors.
運行時lein test :integration
,expensive-fixture
只能運行一次:
› lein test :integration
lein test fixture.core-test
enabling expensive fixture...
doing expensive computation and acquiring resources...
first integration test
yay, expensive thing is done!
second integration test
Ran 2 tests containing 0 assertions.
0 failures, 0 errors.