Skip to content

Commit 57b28b5

Browse files
committed
feat: pass arguments to mocked functions
Previously arguments passed to mocked functions were lost, e.g. when mocking `docker` we had no chance to differentiate between `docker stop` and `docker inspect`. Pass all arguments from the caller to the mocked function now in order to make mocking more flexible.
1 parent 14baf6f commit 57b28b5

3 files changed

Lines changed: 35 additions & 1 deletion

File tree

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
- Pass arguments to mocked functions
6+
37
## [0.26.0](https://github.com/TypedDevs/bashunit/compare/0.25.0...0.26.0) - 2025-11-02
48

59
- Add `assert_unsuccessful_code` assertion to check for non-zero exit codes

docs/test-doubles.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,36 @@ function test_example() {
7575
```
7676
:::
7777

78+
All arguments passed to the original call are forwarded to the mocked function, so you can mock different behavior depending on the arguments.
79+
80+
::: code-group
81+
```bash [Example]
82+
mockTool() {
83+
if [[ "$1" == "--version" ]]; then
84+
echo "1.2.3"
85+
return 0
86+
else
87+
echo "tool: '$1' is not a valid command."
88+
return 1
89+
fi
90+
}
91+
92+
test_example() {
93+
local output
94+
mock tool mockTool
95+
96+
output="$(tool --version)"
97+
assert_successful_code
98+
assert_same "1.2.3" "${output}"
99+
100+
output="$(tool foo)"
101+
assert_general_error
102+
assert_contains "is not a valid command" "${output}"
103+
}
104+
105+
```
106+
:::
107+
78108
## spy
79109
> `spy "function"`
80110

src/test_doubles.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ function mock() {
2727
shift
2828

2929
if [[ $# -gt 0 ]]; then
30-
eval "function $command() { $* ; }"
30+
eval "function $command() { $* \"\$@\"; }"
3131
else
3232
eval "function $command() { echo \"$($CAT)\" ; }"
3333
fi

0 commit comments

Comments
 (0)