2017-08-10 47 views
0

如果我的测试设置中的任何步骤失败,我想将此报告为失败,并停止当前deftest块(或当前名称空间)中的任何后续测试。现在的一种方式做到这一点:对clojure中的谓词失败进行失败并停止测试。

(if some-condition-is-ok 
    (do 
    ... do tests) 
    (is (= 1 0) "Failure, condition not met") 

以上:

  1. 报告失败,如果some-condition-is-ok不满足
  2. 不运行任何测试,因为设置条件不成立

除了它不流畅,并且不适合多种条件。我喜欢这样的东西:

(let [;; setup here...] 

    (assert-or-stop-tests some-condition-is-ok) 
    ... continue with tests here 

任何想法在干净的方式做到这一点?

回答

1

你可以用马克·英格better-cond此:

(require '[better-cond.core :as b] 
     '[clojure.test :refer [is]]) 

(def some-condition-is-ok true) 

(def some-other-condition-is-ok false) 

(deftest a-test 
    (b/cond 
    :let [#_"setup here..."] 
    :when (is some-condition-is-ok) 
    :let [_ (is (= 0 1))] 
    :when (is some-other-condition-is-ok) 
    :let [_ (is (= 1 2))])) 

或者,如果你想避免:let [_ ,,,],您可以定义自己的宏:

(defmacro ceasing [& exprs] 
    (when-let [[left & [right & less :as more]] (seq exprs)] 
    (if (= :assert left) 
     `(when (is ~right) 
     (ceasing [email protected])) 
     `(do 
     ~left 
     (ceasing [email protected]))))) 

(deftest b-test 
    (let [#_"setup here..."] 
    (ceasing 
     :assert some-condition-is-ok 
     (is (= 0 1)) 
     :assert some-other-condition-is-ok 
     (is (= 1 2))))) 
+0

这似乎是一个不错的人选,因为它除了clojure核心之外没有任何依赖,尽管我仍然不喜欢':let'绑定外观。 Upvoting,因为这是一个合理的选择,谢谢你的回答山姆 – Josh

+0

@Josh我已经更新了我的答案,以解决你的两个意见。以前它确实具有Clojure核心以外的依赖关系(即,更好的cond),但是我已经改写了“停止”宏而没有更好的cond,并且删除了“:let”绑定。 –

+0

谢谢萨姆 - 我会留下一点点以鼓励其他答案,但希望继续并感谢您修改它 – Josh