Clojure unit-testing. How do I test if a function throws an exception?

我的未来我决定 提交于 2019-12-23 16:27:25

问题


I see there's a way to test if a function throws an exception of class C. But is there a way to test whether a function throws any exception. Or to assert that it should NOT throw an exception?


回答1:


For tests that don't expect exceptions, write your test as normal. Any exceptions thrown will fail the test.

For tests that could throw any exception, then use Exception or Throwable (Exception's superclass).

For example:

(deftest mytest 
  (is (thrown? Exception (/ 1 0))))

(/ 1 0) will throw a java.lang.ArithmeticException but will also be matched by it's parent class java.lang.Exception.

You could also write a not-thrown? macro to do the opposite of the thrown? macro in clojure.test.

As a side note, you generally want to catch more specific errors when you're unit testing, as your code may throw a new unexpected error but your tests will happily pass.



来源:https://stackoverflow.com/questions/32063244/clojure-unit-testing-how-do-i-test-if-a-function-throws-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!