在测试代码时,我也喜欢涵盖失败的情况。
我是 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"]])
最佳答案
您可以使用 (is (thrown? ExpectedExceptionClass body))
测试抛出的异常
见 http://clojure.github.io/clojure/clojure.test-api.html
关于unit-testing - 如何在 Clojure 中测试抛出的异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26301601/