情况是这样的:我正在尝试对调用函数 B 的函数 A 进行单元测试。函数 B 在弹弓 try+ 块中调用,在某些情况下,它可以使用弹弓 throw+ 抛出。我想在 midje 测试中模拟函数 B,以便它返回 try+ 块中的 catch 将实际捕获的内容。我似乎无法创造正确的东西来扔。这是代码和测试的基本简略草图:
(defn function-A
[param]
(try+
(function-B param)
(catch [:type :user-not-found]
(do-something))))
(defn function-B
[param]
(throw+ [:type :user-not-found]))
(fact "do-something is called"
(function-A "param") => (whatever is the result of calling do-something)
(provided
(function-B "param") =throws=> (clojure.lang.ExceptionInfo. "throw+: {:type :user-not-found}"
{:object {:type :user-not-found}, :environment {}}
nil)))
我抛出的 ExceptionInfo 似乎大致正确。当我的应用程序通过大量 prn 语句运行时,我可以看到这一点。但是,无论我尝试什么,我都无法让测试工作。
我还在 repl 中尝试了下面的代码,看看我是否能理解这个问题。然而,虽然两段代码似乎都涉及相同的异常,但只有一个(纯弹弓的)设法捕获并打印“捕获它”。我认为如果我能理解为什么一个有效而另一个无效,我将能够通过单元测试解决问题。
(try+
(try
(throw+ {:type :user-not-found})
(catch Exception e
(prn "Caught: " e)
(prn "Class: " (.getClass e))
(prn "Message: " (.getMessage e))
(prn "Cause: " (.getCause e))
(prn "Data: " (.getData e))
(throw e)))
(catch [:type :user-not-found] p
(prn "caught it")))
(try+
(try
(throw (clojure.lang.ExceptionInfo. "throw+: {:type :user-not-found}"
{:object {:type :user-not-found}, :environment {}}
nil))
(catch Exception e
(prn "Caught: " e)
(prn "Class: " (.getClass e))
(prn "Message: " (.getMessage e))
(prn "Cause: " (.getCause e))
(prn "Data: " (.getData e))
(throw e)))
(catch [:type :user-not-found] p
(prn "caught it")))
最佳答案
这是一个非常晚的响应,但是以下解决方案呢:
(defn ex+ [cause]
(try
(throw+ cause)
(catch Throwable ex
ex)))
用法示例:
(broken-fn) =throws=> (ex+ {:type :user-not-found})
好处是您不依赖于 Slingshot 的内部实现。
关于unit-testing - 为什么我不能使用 midje 来模拟使用弹弓的 throw+ 抛出的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17069584/