在 midje 中模拟函数调用

mocking a function call in midje

假设我有一个函数

(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

为了模拟内部事务失败,什么是对该函数调用进行存根(仅在某些情况下)的好方法。

你可以使用 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 代替函数参数将函数存根到 return 一个值,无论输入参数如何:

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