clojure - 如何编写测试来处理预期的异常?

标签 clojure leiningen

如何测试抛出预期异常的函数?这是引发异常的函数:

(defn seq-of-maps?
  "Tests for a sequence of maps, and throws a custom exception if not."
  [s-o-m]
  (if-not (seq? s-o-m)
    (throw (IllegalArgumentException. "s-o-m is not a sequence"))
    (if-not (map? (first s-o-m))
      (throw (IllegalArgumentException. "s-o-m is not a sequence of maps."))
      true)))

我想设计一个如下所示的测试,在该测试中抛出并捕获异常,然后进行比较。以下不起作用:
(deftest test-seq-of-maps
  (let [map1  {:key1 "val1"}
        empv  []
        s-o-m (list {:key1 "val1"}{:key2 "val2"})
        excp1 (try 
                (seq-of-maps? map1)
                (catch Exception e (.getMessage e)))]
    (is (seq-of-maps? s-o-m))
    (is (not (= excp1 "s-o-m is not a sequence")))))

我收到这些错误:
Testing util.test.core

FAIL in (test-seq-of-maps) (core.clj:27)
expected: (not (= excp1 "s-o-m is not a sequence"))
  actual: (not (not true))

Ran 2 tests containing 6 assertions.
1 failures, 0 errors.    

显然,我遗漏了一些关于编写测试的东西。我很难弄清楚。我的项目是用 lein new 建立的,我正在用 lein test 运行测试。

谢谢。

最佳答案

测试中的最后一个断言不正确;应该是 (is (= excp1 "s-o-m is not a sequence"))因为 map1 不是 map 序列。

除此之外,使用 (is (thrown? ..)) or (is (thrown-with-msg? ...)) 可能更清楚。检查抛出的异常。

示例:

(t/is (thrown? java.lang.ClassCastException (s/valid? ::sut/int-value "x"))))

请注意,您只需将类名写为符号。使用java.lang.Exception如果您不关心确切的 Exception .

关于clojure - 如何编写测试来处理预期的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11973234/

相关文章:

clojure - Core.logic的简要说明

clojure - Clojure 中最简单的惰性函数

Clojure BigInt 不是 Java BigInteger

clojure - 使用 postwalk 将节点添加到树

debugging - 使用 swank-cdt 调试 clojure 时出错 : "unabled to add tools.jar to classpath"

clojure - 如何在我的 Clojure 应用程序中嵌入 REPL?

clojure - 如何解决 "No credentials found for releases (did you mean ` lein部署clojars`?)”?

clojure - lein-autodoc 与 Leiningen 2

linux - 无法为 Ubuntu 安装 LightTable

ubuntu - lein run 命令从 xterm 引发异常时失败