Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test for thrown exceptions in Clojure?

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"]])
like image 352
Edward Avatar asked Oct 10 '14 14:10

Edward


1 Answers

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

See http://clojure.github.io/clojure/clojure.test-api.html

like image 158
Joost Diepenmaat Avatar answered Sep 28 '22 04:09

Joost Diepenmaat