简体   繁体   中英

clojure test that assertion throws

I have a function defined as:

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

And then I have a test for it:

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

However this test fails:

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

What is needed to check that the assertion would throw an error?

The reason your assertion fails because you are nesting two is . The inner is already catches the exception so the outer is test then fails because nothing is thrown.

(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM