简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM