【发布时间】:2015-09-15 12:04:05
【问题描述】:
我在测试 clojure 宏时遇到了一些问题。当我将代码放入 repl 时,它的行为与预期一样,但是当我尝试在测试中期待这种行为时,我却得到了 nil 。我觉得这与测试运行程序如何处理宏扩展有关,但我不确定到底发生了什么。感谢任何测试此代码的建议/替代方法。
这是我正在尝试测试的宏的简化示例
(defmacro macro-with-some-validation
[-name- & forms]
(assert-symbols [-name-])
`(defn ~-name- [] (println "You passed the validation")))
(macroexpand-1 (read-string "(macro-with-some-validation my-name (forms))"))
;; ->
(clojure.core/defn my-name [] (clojure.core/println "You passed the validation"))
传入repl时
(macroexpand-1 (read-string "(macro-with-some-validation 'not-symbol (forms))"))
;; ->
rulesets.core-test=> Exception Non-symbol passed in to function. chibi-1-0-0.core/assert-symbols (core.clj:140)
但是当通过测试时
(deftest macro-with-some-validation-bad
(testing "Passing in a non-symbol to the macro"
(is (thrown? Exception
(macroexpand-1 (read-string "(macro-with-some-validation 'not-symbol (forms))"))))))
;; after a lein test ->
FAIL in (macro-with-some-validation-bad) (core_test.clj:50)
Passing in a non-symbol to the macro
expected: (thrown? Exception (macroexpand-1 (read-string "(macro-with-some-validation 'not-symbol (forms))")))
actual: nil
谢谢。
编辑:忘记包含断言符号的来源,以防万一
(defn assert-symbol [symbol]
(if (not (instance? clojure.lang.Symbol symbol))
(throw (Exception. "Non-symbol passed in to function."))))
(defn assert-symbols [symbols]
(if (not (every? #(instance? clojure.lang.Symbol %) symbols))
(throw (Exception. "Non-symbol passed in to function."))))
【问题讨论】: