1

说我有一个功能

(defn extenal_api_fn [stuff]
   ... do things....
)

(defn register_user [stuff]
  (external_api_fn stuff))

然后是一个测试

(def stuff1
  {:user_id 123 })

(def stuff2
  {:user_id 234})

(background (external_api_fn stuff1) => true
            (with-redefs [external_api_fn (fn [data] (println "mocked function"))]
            (register_user stuff1) => true)
            (register_user stuff2) => true)

(facts "stuff goes here"
  (fact "user that registers correctly
    (= 1 1) => truthy)
  (fact "user that has a registration failure"
    (= 1 2) => falsy))

这失败了

"you never said #'external_api_fn" would be called with these arguments:
    contents of stuff1

什么是存根这个函数调用(仅在某些情况下)以模拟内部事务失败的好方法。

4

1 回答 1

1

您可以使用 Midje 的provided

(fact
  (register_user stuff1) => :registered
  (provided
    (extenal_api_fn stuff1) => :registered))

(fact
  (register_user stuff2) => :error
  (provided
    (external_api_fn stuff2) => :error))

anything您还可以通过使用代替函数参数来存根函数以返回值,无论输入参数如何:

(fact
  (register_user stuff2) => :error
  (provided
    (external_api_fn anything) => :error))
于 2016-10-14T16:59:45.927 回答