How can I check for thrown exceptions in Clojure?
When testing code, I also like the failure conditions.
I'm new to Clojure, but how can I test a thrown exception?
I would like to test the following example code:
(ns com.stackoverflow.clojure.tests)
(defn casetest [x]
(case x
"a" "An a."
"b" "A b."
(-> (clojure.core/format "Expression '%s' not defined." x)
(IllegalArgumentException.)
(throw))))
with the following test methods:
(ns com.stackoverflow.clojure.tests-test
(:require [clojure.test :refer :all]
[com.stackoverflow.clojure.tests :refer :all]))
(deftest casetest-tests
(is (= "An a." (casetest "a")))
(is (= "A b." (casetest "b")))
(throws-excpeption IllegalArgumentException. (casetest "c")) ; conceptual code
)
(run-tests)
My .clj project looks like this:
(defproject com.stackoverflow.clojure/tests "0.1.0-SNAPSHOT"
:description "Tests of Clojure test-framework."
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]])
+3
source to share