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)


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



My .clj project looks like this:

(defproject com.stackoverflow.clojure/tests "0.1.0-SNAPSHOT"
  :description "Tests of Clojure test-framework."
  :url ""
  :license {:name "Eclipse Public License"
            :url ""}
  :dependencies [[org.clojure/clojure "1.6.0"]])



source to share

1 answer

You can test the thrown exception with (is (thrown? ExpectedExceptionClass body))




All Articles