Clojure方法参数类型检查单元测试断言异常问题求助
解决Clojure单元测试中
thrown?断言未捕获ExceptionInfo的问题 问题原因
你的测试代码里多了一层不必要的try/catch。clojure.test的thrown?宏本身会自动捕获目标异常类型,而你手动加的try/catch会把异常直接抛出,跳过了thrown?的断言逻辑,导致测试框架认为这是一个未在断言中处理的异常,所以报错“expected: nil”。
修正后的测试代码
去掉冗余的try/catch块,直接调用目标方法即可:
(testing "test bad input schema" (let [candidates [{:bad-attr1 "123" :bad-attr2 "456"}] goal {:id "123" }] (is (thrown? ExceptionInfo (my-class/my-method candidates goal)))))
额外优化建议
- 你在
my-method里手动调用s/validate属于重复操作:使用s/defn定义函数时,Schema会自动验证入参和返回值的格式,不需要手动遍历验证每个candidate,也不需要单独验证goal,可以删掉这些手动验证代码简化实现。 - 如果需要更精确地验证异常内容,可以用
thrown-with-msg?宏同时检查异常类型和错误消息:
(is (thrown-with-msg? ExceptionInfo #"Value does not match schema" (my-class/my-method candidates goal)))
内容的提问来源于stack exchange,提问作者Laodao
相关产品推荐
相关产品推荐

