如何使用`with-redefs`总是抛出函数异常

Joe*_*oel 3 unit-testing clojure

我想对代码的异常处理部分进行单元测试。为了做到这一点,我使用with-redefs了重新绑定可以抛出异常的API来在测试期间抛出异常。我的测试功能看起来像这样

(deftest exception-handling
  (testing "Map exception to Ring-response map"
    (with-redefs [clj-http/get
                  (constantly (throw (ex-info "unexpected error" {:cause "A terrible calamity"})))]
      (is (= 500
        (:status
          (some-function-calling-http-get arg))))
    )
  )
)
Run Code Online (Sandbox Code Playgroud)

运行会lein test导致错误消息:

    ERROR in (exception-handling) (core.clj:4593)
Uncaught exception, not in assertion.
expected: nil
  actual: clojure.lang.ExceptionInfo: unexpected error
 at clojure.core$ex_info.invoke (core.clj:4593)
Run Code Online (Sandbox Code Playgroud)

使用(constantly (throw...in with-redefs或仅断言抛出了一个异常thrown?也会导致相同的错误。

本质上,我正在寻找的宏版本constantly

Leo*_*tny 5

constantly是一个函数,而不是宏,因此(constantly (throw ...))会立即引发错误。

如果您想要一个每次调用都会抛出错误的函数,则需要类似以下内容:

(with-redefs [clj-http/get (fn [& _] (throw (ex-info "unexpected error"
                                                     {:cause "A terrible calamity"})))]
  ...)
Run Code Online (Sandbox Code Playgroud)