我想对代码中的异常处理部分进行单元测试。为了做到这一点,我使用with-redefs重新绑定API,该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))))
)
)
)运行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)在(constantly (throw...中使用with-redefs或仅仅断言使用thrown?引发异常也会导致相同的错误。
本质上,我在寻找constantly的宏版本。
发布于 2015-11-10 09:01:45
constantly是一个函数,而不是宏,因此(constantly (throw ...))会立即抛出一个错误。
如果您想要在每次调用错误时抛出错误的函数,则需要这样的操作:
(with-redefs [clj-http/get (fn [& _] (throw (ex-info "unexpected error"
{:cause "A terrible calamity"})))]
...)发布于 2015-11-10 09:05:12
您的方法是错误的:您的测试期望clj-http的正常行为返回状态500,但是您的with-redef实际上完全覆盖了任何clj-http代码。换句话说,您的测试显示,所有对clj-http/get现在总是(constantly)的调用都会引发异常。相反,您想要的是clj-http/get总是返回一个500。您可以通过使用clj-http-假来做到这一点。
发布于 2015-11-10 11:33:48
您还可以使用clj-http-假模拟对外部世界的HTTP调用,例如。
(with-fake-routes {
"http://external.api" (fn [request] {:status 500 :headers {} :body "Exception"}
(is (= 500
(:status
(some-function-calling-http-get arg))))))https://stackoverflow.com/questions/33625888
复制相似问题