Clojure: How To use-fixtures in Testing

前端 未结 1 1523
一整个雨季
一整个雨季 2021-01-04 08:31

I am writing some unit tests that interact with a database. For this reason it is useful to have a setup and a teardown method in my unit test to create and then drop the ta

相关标签:
1条回答
  • 2021-01-04 09:19

    You can't use use-fixtures to provide setup and teardown code for freely defined groups of tests, but you can use :once to provide setup and teardown code for each namespace:

    ;; 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 ... )
    

    This approach forces some coupling between setup and teardown code and the packages the tests are in, but generally that's not a huge problem. You can always do your own manual wrapping in testing sections, see for example the bottom half of this blog post.

    0 讨论(0)
提交回复
热议问题