20

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

(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 运行测试。

谢谢。

4

1 回答 1

20

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

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

例子:

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

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

于 2012-08-15T17:54:29.717 回答