2

我尝试测试异常的抛出:

;;; 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))))

但是没有一个异常被测试框架捕获,而是全部抛出。

4

2 回答 2

2

你的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}
于 2013-06-28T16:49:12.193 回答
1

之所以仍然抛出异常,是因为宏(my-macro)在编译时被扩展,调用(assert-args)宏,因此在编译时抛出异常。我的错误是假设调用(my-macro)测试将在运行时触发异常并让测试(thrown-with-msg?)捕获它。

所以错误的假设是嵌套宏的代码仅在编译期间扩展,而不是执行。如果(my-macro)将是一个功能,这将是有效的。

于 2013-07-10T08:47:44.393 回答