【问题标题】:How to test for thrown exceptions in Clojure?如何在 Clojure 中测试抛出的异常?
【发布时间】:2014-10-10 14:19:29
【问题描述】:

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

我是 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"]])

【问题讨论】:

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


    【解决方案1】:

    您可以使用(is (thrown? ExpectedExceptionClass body)) 测试抛出的异常

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

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 2023-01-25
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 2018-02-13
      • 2020-08-18
      • 2014-05-10
      相关资源
      最近更新 更多