When testing code I like to cover failing conditions, too.
I'm new to Clojure, but is it somehow possible to test for a thrown exception?
I'd like to test the following sample 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 project.clj looks like:
(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"]])
You can test for a thrown exception with (is (thrown? ExpectedExceptionClass body))
See http://clojure.github.io/clojure/clojure.test-api.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With