1

假设我正在尝试测试一个应该处理某些对象字段的存在或不存在的 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")

哪个通过了。我的问题是。功能tabularfacts功能有何不同,为什么其中一个接受against-background而另一个爆炸?

4

1 回答 1

2

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

(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-backgroundor中fact

例如:

(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.

在您的代码中,表格数据的位置似乎不正确(括号、方括号和花括号未正确平衡,因此无法说出究竟是什么不正确)。

于 2016-10-24T18:56:37.220 回答