Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 720
interstar Avatar asked Aug 18 '15 03:08

interstar


1 Answers

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.

like image 134
Daniel Compton Avatar answered Nov 08 '22 14:11

Daniel Compton