Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何使用redefs模拟对同一函数的多个调用?_Unit Testing_Clojure_Mocking_Compojure - Fatal编程技术网

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的示例