unit-testing - 为什么我不能使用 midje 来模拟使用弹弓的 throw+ 抛出的函数

标签 unit-testing exception-handling clojure mocking midje

情况是这样的:我正在尝试对调用函数 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/

相关文章:

c++ - 使用GTest重复多次多线程测试的正确方法是什么?

java - 编写库(不是应用程序)时如何处理异常 - Java

.net - WCF Windows 服务超时

exception-handling - 应该如何处理 ColdFusion 异常和 404 错误?

clojure - Clojure 中的交互式动态绘图/图表

Clojure 整数溢出

c# - 如何使用 Mock.Of<T>() 模拟没有默认构造函数的类?

Django:测试客户端的上下文在 shell 中为空

node.js - 断言错误: expeced to be called once but was called 0 times

clojure - 在 Clojure 中逐字符处理文件