【问题标题】:clojure test that assertion throws断言抛出的clojure测试
【发布时间】:2016-11-30 19:41:19
【问题描述】:

我有一个函数定义为:

(defn strict-get
  [m key]
  {:pre [(is (contains? m key))]}
  (get m key))

然后我对其进行了测试:

(is (thrown? java.lang.AssertionError (strict-get {} :abc)))

但是这个测试失败了:

  ;; FAIL in () (myfile.clj:189)
  ;; throws exception when key is not present
  ;; expected: (contains? m key)
  ;; actual: (not (contains? {} :abc))

需要什么来检查断言是否会引发错误?

【问题讨论】:

标签: clojure clojure.test


【解决方案1】:

您的断言失败的原因是您嵌套了两个is。内部 is 已经捕获到异常,因此外部 is 测试然后失败,因为没有抛出任何东西。

(defn strict-get
  [m key]
  {:pre [(contains? m key)]} ;; <-- fix
  (get m key))

(is (thrown? java.lang.AssertionError (strict-get {} nil)))
;; does not throw, but returns exception object for reasons idk

(deftest strict-get-test
  (is (thrown? java.lang.AssertionError (strict-get {} nil))))

(strict-get-test) ;; passes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2014-04-25
    • 2014-09-21
    相关资源
    最近更新 更多