如何测试抛出预期异常的函数?这是引发异常的函数:
(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 运行测试。
谢谢。