【问题标题】:Mocking requests for multiple tests cause side effect多个测试的模拟请求会导致副作用
【发布时间】:2018-09-09 22:05:26
【问题描述】:

我为我的 API 创建了 2 个“功能”测试,当我使用 lein test 一次运行所有测试时,来自一个测试的请求会在下一个测试用例中传播。 我想知道是否有办法在运行 deftest 后取消模拟或撤消请求。

我正在使用ring/ring-mock,使用ring.mock.request/mock 模拟请求,我正在使用leingein 运行测试

file1.clj

(deftest some-test
  (testing ""
    (app (-> (mock/request :post "/some-endpoint")
    (mock/content-type "application/json")
    (mock/body (cheshire/generate-string {:some "value"}))))

file2.clj

(deftest some-other-test-file
  (testing ""
    (let [response (app (-> (mock/request :get "/some-endpoint"))]
        ; response has {:some "value"}
)))

【问题讨论】:

  • 是的。但由于它是一个功能测试,因此我在发布某些内容时重新定义的变量不能从我的测试文件中使用with-redefs
  • 你能添加示例代码来显示问题吗?
  • @AlanThompson 的伪代码够清楚吗?
  • 请记住,with-redef 使我们严格不适合并行运行测试。它不是线程安全的。如果您想使用它,您需要确保它已被使用,以便它包装所有将并行运行的测试。

标签: clojure leiningen ring


【解决方案1】:

您似乎想使用Clojure test fixtures。这些允许您使用测试前调用的设置函数和测试后调用的清理函数来包装测试(单独或作为组)。

这是一个例子from ClojureDocs.com

; See https://clojure.github.io/clojure/clojure.test-api.html for details

; my-test-fixture will be passed a fn that will call all your tests 
; (e.g. test-using-db).  Here you perform any required setup 
; (e.g. create-db), then call the passed function f, then perform 
; any required teardown (e.g. destroy-db).
(defn my-test-fixture [f]
        (create-db)
        (f)
        (destroy-db))

; Here we register my-test-fixture to be called once, wrapping ALL tests 
; in the namespace
(use-fixtures :once my-test-fixture)

; This is a regular test function, which is to be wrapped using my-test-fixture
(deftest test-using-db
  (is ... 
))

【讨论】:

  • 我明白你的意思。问题是我试图隔离测试中的更改,而不是手动执行和撤消它。但我会尝试使用固定装置。
  • @bpereira 没有更多关于你正在跟踪什么样的状态并试图“保持孤立”的信息,没有比艾伦所说的更好的答案了。根据您的回答,我的猜测是您的经验是使用“神奇地”为您解决隔离问题的测试套件,但如果您深入了解一下,您会发现他们正在按照 Alan 的建议行事。跨度>
猜你喜欢
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-20
  • 2019-01-26
  • 2015-08-27
  • 1970-01-01
相关资源
最近更新 更多