如何测试抛出预期异常的函数?这是抛出异常的函数:
(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测试运行测试。
感谢。
答案 0 :(得分:16)
你的测试中的最后一个断言是不正确的;它应该是(is (= excp1 "s-o-m is not a sequence"))
,因为map1不是地图的seq。
除此之外,使用(is (thrown? ..))
或(is (thrown-with-msg? ...))
来检查抛出异常可能更清楚。