如何测试Clojure中的抛出异常?

时间:2014-10-10 14:19:29

标签: unit-testing exception testing exception-handling clojure

在测试代码时,我也喜欢涵盖失败的条件。

我是Clojure的新手,但在某种程度上可以测试抛出的异常吗?

我想测试以下示例代码:

(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))))

使用以下测试方法:

(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)

我的project.clj看起来像:

(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"]])

1 个答案:

答案 0 :(得分:4)

您可以使用(is (thrown? ExpectedExceptionClass body))

测试抛出的异常

请参阅http://clojure.github.io/clojure/clojure.test-api.html