From e116cadb079566fc2e72746ebb7fb0d442d96838 Mon Sep 17 00:00:00 2001 From: Philipp Meier Date: Thu, 7 Mar 2024 12:01:32 +0100 Subject: [PATCH] Add `returning` to support multiple results for function invocation. This follows the suggestion in #10 --- doc/documentation.md | 13 +++++++++++++ src/mockfn/macros.cljc | 10 ++++++++++ test/mockfn/examples/basic_usage.cljc | 6 ++++++ 3 files changed, 29 insertions(+) diff --git a/doc/documentation.md b/doc/documentation.md index 0909696..ebba9d5 100644 --- a/doc/documentation.md +++ b/doc/documentation.md @@ -59,6 +59,19 @@ If you would like to call the value instead of returning it, use `mockfn.macros/ (is (thrown? ExceptionInfo (one-fn))))) ``` +#### `returning` + +If you want to return different values for each invocation, use `mockfn.macros/returning`. +Note that if the function will return `nil` afer all provided results are consumed. + +```clj +(testing "providing - cause function non referential" + (mfn/providing [(one-fn :argument-1) (mfn/returning :result-1 :result-2 )] + (is (= :result-1 (one-fn :argument-1))) + (is (= :result-2 (one-fn :argument-1))) + (is (nil? (one-fn :argument-1))))) +``` + #### `fall-through` When mocking a function, it is sometimes useful to allow calls with specific diff --git a/src/mockfn/macros.cljc b/src/mockfn/macros.cljc index e1cc96c..b720ea5 100644 --- a/src/mockfn/macros.cljc +++ b/src/mockfn/macros.cljc @@ -32,3 +32,13 @@ (doseq [mock# ~(into [] (keys specs#))] (mock/verify mock#)) res#)))) + +(defn returning + "Returns one value after the other. Used with `calling`" + [& values] + (let [stack (atom (into [] (reverse values))) + next (fn [_] (let [ret (peek @stack)] + (when-not (empty? @stack) + (swap! stack pop)) + ret))] + (calling next))) diff --git a/test/mockfn/examples/basic_usage.cljc b/test/mockfn/examples/basic_usage.cljc index bb47e69..7614ffb 100644 --- a/test/mockfn/examples/basic_usage.cljc +++ b/test/mockfn/examples/basic_usage.cljc @@ -25,6 +25,12 @@ (is (thrown? ExceptionInfo (one-fn :argument-1))) (is (= :result-2 (one-fn :argument-2))))) + (testing "providing - cause function returns different results" + (mfn/providing [(one-fn :argument-1) (mfn/returning :result-1 :result-2 )] + (is (= :result-1 (one-fn :argument-1))) + (is (= :result-2 (one-fn :argument-1))) + (is (nil? (one-fn :argument-1))))) + (testing "providing with more than one function" (mfn/providing [(one-fn :argument) :result-1 (other-fn :argument) :result-2]