gpt4 book ai didi

unit-testing - 如何在使用 throw-with-msg 的测试中捕获 IllegalArgumentException?

转载 作者:行者123 更新时间:2023-12-04 04:51:31 25 4
gpt4 key购买 nike

我尝试测试异常的抛出:

;;; src
;; Courtesy https://github.com/clojure/clojure/blob/master/src/clj/clojure/core.clj
(defmacro assert-args [& pairs]
`(do (when-not ~(first pairs)
(throw (IllegalArgumentException.
(str (first ~'&form) " requires " ~(second pairs) " in " ~'*ns* ":" (:line (meta ~'&form))))))
~(let [more (nnext pairs)]
(when more
(list* `assert-args more)))))

(defmacro my-macro []
(assert-args false "foobar")
#_(...))

;;; test
(deftest x-fn-test
(is (thrown-with-msg? IllegalArgumentException #"foo" (my-macro))))

但是测试框架没有捕获任何异常,而是全部抛出。

最佳答案

您的 throw表达式格式错误,你想要

(throw (IllegalArgumentException. "foo"))

完整的工作代码:
(ns mytest.core
(:use clojure.test))

(defn x-fn []
(throw (IllegalArgumentException. "foo")))

(deftest x-fn-test
(is (thrown-with-msg? IllegalArgumentException #"foo" (x-fn)))
(is (thrown-with-msg? IllegalArgumentException #".*foo.*" (x-fn)))
(is (thrown-with-msg? IllegalArgumentException #"^foo$" (x-fn)))
(is (thrown-with-msg? java.lang.IllegalArgumentException #"foo" (x-fn)))
(is (thrown-with-msg? java.lang.IllegalArgumentException #".*foo.*" (x-fn)))
(is (thrown-with-msg? java.lang.IllegalArgumentException #"^foo$" (x-fn))))


; nREPL 0.1.8-preview
user>
#<Namespace mytest.core>
mytest.core> (run-tests)

Testing mytest.core

Ran 1 tests containing 6 assertions.
0 failures, 0 errors.
{:type :summary, :pass 6, :test 1, :error 0, :fail 0}

关于unit-testing - 如何在使用 throw-with-msg 的测试中捕获 IllegalArgumentException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17369580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com