Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add returning to support multiple results for function invocation. #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add returning to support multiple results for function invocation.
This follows the suggestion in #10
  • Loading branch information
phmeier-nubank committed Mar 7, 2024
commit e116cadb079566fc2e72746ebb7fb0d442d96838
13 changes: 13 additions & 0 deletions doc/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/mockfn/macros.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
6 changes: 6 additions & 0 deletions test/mockfn/examples/basic_usage.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading