表格测试的测试先决条件;表格是如何工作的



假设我正在尝试测试一个api,该api应该处理某些对象字段的存在或不存在。

假设我有这样的测试:

(def without-foo
   {:bar "17"})
(def base-request
   {:foo "12"
    :bar "17"})
(def without-bar
   {:foo "12"})
(def response
  {:foo  "12"
   :bar  "17"
   :name "Bob"})
(def response-without-bar
  {:foo  "12"
   :bar  ""
   :name "Bob"})
(def response-without-foo
  {:bar  "17"
   :foo  ""
   :name "Bob"})
(facts "blah"
  (against-background [(external-api-call anything) => {:name => "Bob"})
  (fact "base"
    (method-under-test base-request) => response)
  (fact "without-foo"
    (method-under-test without-foo) => response-without-foo)
  (fact "without-bar"
    (method-under-test without-bar) => response-without-bar))

按照您的期望工作,并且测试通过了。现在我尝试用表格来重构它,像这样:

(def request
  {:foo "12"
   :bar "17"})
(def response
  {:foo  "12"
   :bar  "17"
   :name "Bob"})
(tabular
  (against-background [(external-api-call anything) => {:name "Bob"})]
  (fact 
    (method-under-test (merge request ?diff) => (merge response ?rdiff))
  ?diff          ?rdiff             ?description
  {:foo nil}     {:foo ""}          "without foo"
  {}             {}                 "base case"
  {:bar nil}     {bar ""}           "without bar")

结果是:

FAIL at (test.clj:123)
  Midje could not understand something you wrote:
    It looks like the table has no headings, or perhaps you
    tried to use a non-literal string for the doc-string?

最后我写了:

(tabular
  (fact 
    (method-under-test (merge request ?diff) => (merge response ?rdiff) (provided(external-api-call anything) => {:name "Bob"}))
  ?diff          ?rdiff             ?description
  {:foo nil}     {:foo ""}          "without foo"
  {}             {}                 "base case"
  {:bar nil}     {bar ""}           "without bar")

传递。我的问题是。tabular函数和facts函数有什么不同,为什么其中一个接受against-background而另一个爆炸?

如果您想为所有基于表格的事实建立背景先决条件,则需要有以下嵌套:

(against-background [...]
  (tabular
    (fact ...)
    ?... ?...))
例如:

(require '[midje.repl :refer :all])
(defn fn-a []
  (throw (RuntimeException. "Not implemented")))
(defn fn-b [k]
  (-> (fn-a) (get k)))
(against-background
  [(fn-a) => {:a 1 :b 2 :c 3}]
  (tabular
    (fact
      (fn-b ?k) => ?v)
    ?k ?v
    :a 1
    :b 3
    :c 3))
(check-facts)
;; => All checks (3) succeeded.

如果你想为每个表格大小写设置一个背景条件,你需要像下面这样嵌套它:

(表格(以背景[…](事实…))?…

?…)

将表放在tabular级别下,而不是嵌套在against-backgroundfact中,这一点很重要。

例如:

(require '[midje.repl :refer :all])
(defn fn-a []
  (throw (RuntimeException. "Not implemented")))
(defn fn-b [k]
  (-> (fn-a) (get k)))
(tabular
  (against-background
    [(fn-a) => {?k ?v}]
    (fact
      (fn-b ?k) => ?v))
  ?k ?v
  :a 1
  :b 2
  :c 3)
(check-facts)
;; => All checks (3) succeeded.

在你的代码中,它看起来像表格数据没有正确定位(括号,括号和花括号没有正确平衡,所以不可能说什么是不正确的)。

最新更新