oct*_*bus 15 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)))
Run Code Online (Sandbox Code Playgroud)
我想设计一个如下所示的测试,其中抛出异常并捕获然后进行比较.以下不起作用:
(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")))))
Run Code Online (Sandbox Code Playgroud)
我收到这些错误:
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.
Run Code Online (Sandbox Code Playgroud)
显然,我缺少一些关于编写测试的东西.我很难搞清楚这一点.我的项目是用lein new建立的,我用lein测试运行测试.
谢谢.
Joo*_*aat 18
测试中的最后一个断言是不正确的; 它应该是(is (= excp1 "s-o-m is not a sequence"))因为map1不是map的seq.
除此之外,使用(is (thrown? ..))或(is (thrown-with-msg? ...))检查抛出的异常可能更清楚.