繁体   English   中英

clojure.test((抛出?)没有看到异常

[英]clojure.test (is (thrown? …) not seeing exception

我有一个函数param-values ,当它在Liberator上下文中找不到键时会抛出IllegalArgumentException 我对此有一个clojure.test单元测试:

(testing "Non-existing key" 
  (is (thrown? IllegalArgumentException (param-values ctx [:baz]))))

由于某种原因,即使我可以看到我的功能在REPL中的行为正确,此测试也失败了:

user> (param-values ctx [:baz])
IllegalArgumentException Missing required param baz  resources/param-value (resources.clj:57)

user> (is (thrown? IllegalArgumentException (param-values ctx [:baz])))

FAIL in clojure.lang.PersistentList$EmptyList@1 (form-init2687593671136401208.clj:1)
expected: (thrown? IllegalArgumentException (param-values ctx [:baz]))
  actual: nil

param-values本身很简单; 它只是映射具有param-value的指定args:

(defn param-values [ctx args & [{:keys [optional-args] :as opts}]]
  (let [params (or (get-in ctx [:request :params]) {})
        args (concat args optional-args)]
    (map #(param-value params % opts) args)))

当然,我对param-value进行了更深入的测试,其中之一是:

(testing "Arg not present"
    (is (thrown-with-msg?
         IllegalArgumentException #"Missing required param baz"
         (param-value {} :baz))))

该测试通过!

是什么赋予了? 关于我不喜欢clojure.test/is宏的事情吗? 我有错别字吗?

是否因为param-values返回了惰性序列?

当使用thrown-with-msg? 它根据(param-value {} :baz)的返回值调用re-find ,从而评估延迟序列。 仅使用thrown?时不会发生这种情况thrown? 代替。

所以您可以尝试以下方法:

(is (thrown? IllegalArgumentException
      (doall (param-values ctx [:baz]))))

doall将评估延迟序列。


根据评论更新

由于您对延迟序列的返回值不感兴趣,而仅对副作用(引发异常) dorun ,因此最好使用dorun而不是doall

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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