情况是这样的:我正在尝试对调用函数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")))发布于 2013-06-13 01:53:30
根据slingshot关于如何生成可抛出对象的代码(参见here,here和here),我发现了以下(有些人为的)方法来生成一个可抛出对象,它可以在仅使用throw时工作。
(s/get-throwable (s/make-context {:type :user-not-found} "throw+: {:type :user-not-found}" (s/stack-trace) {}))这将呈现您期望从示例中得到的结果。
(try+
(try
(throw (s/get-throwable (s/make-context {:type :user-not-found} "throw+: {:type :user-not-found}" (s/stack-trace) {})))
(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")))希望能有所帮助。
发布于 2016-02-05 15:44:10
这是一个非常晚的响应,但是下面的解决方案如何:
(defn ex+ [cause]
(try
(throw+ cause)
(catch Throwable ex
ex)))使用示例:
(broken-fn) =throws=> (ex+ {:type :user-not-found})好处是您不需要依赖Slingshot的内部实现。
https://stackoverflow.com/questions/17069584
复制相似问题