Unit testing 如何使用redefs模拟对同一函数的多个调用?
我希望能够模拟Unit testing 如何使用redefs模拟对同一函数的多个调用?,unit-testing,clojure,mocking,compojure,Unit Testing,Clojure,Mocking,Compojure,我希望能够模拟MyFunction,但是我需要模拟在调用MyFunction时返回不同的值 是否可以将与redefs一起使用根据函数的调用顺序返回不同的值 (testing "POST /foo/bar and return ok" (with-redefs [->Baz (fn [_] (reify MyProtocol (MyFunction [_] [{:something 1}])) (reify
MyFunction
,但是我需要模拟在调用MyFunction
时返回不同的值
是否可以将与redefs一起使用
根据函数的调用顺序返回不同的值
(testing "POST /foo/bar and return ok"
(with-redefs [->Baz (fn [_]
(reify MyProtocol (MyFunction [_] [{:something 1}]))
(reify MyProtocol (MyFunction [_] [{:something 2}])))]
(let [response (routes/foo {:request-method :post
:uri "/foo/bar"
:query-params {}
})]
(is (= (:status response) 200)))))
您可以使用返回值的可变集合,然后在每次调用时从中返回/删除值
(defn foo [x] (inc x)) ;; example fn to be mocked
如果要模拟对foo
的三个调用,分别返回1、2和3:
(with-redefs [foo (let [results (atom [1 2 3])]
(fn [_] (ffirst (swap-vals! results rest))))]
(prn (foo 0))
(prn (foo 0))
(prn (foo 0))
;; additional calls would return nil
(prn (foo 0)))
;; 1
;; 2
;; 3
;; nil
使用交换VAL
获取atom的旧/新值,但需要Clojure 1.9或更高版本
如果您没有交换VAL代码>您可以这样做(减少原子性):
(with-redefs [foo (let [results (atom [1 2 3])]
(fn [_]
(let [result (first @results)]
(swap! results rest)
result)))]
...)
为此,我们使用Picomock,并断言每个调用的参数,以及断言调用的数量。推荐 我得到无法解析符号:交换VAL!在此上下文中
@Freid001交换VAL
是在Clojure 1.9中引入的,因此您必须使用以前的版本。我更新了另一个不使用交换VAL的示例代码>。