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

FAQ entry on calling un-patched function inside patch #136

Merged
merged 3 commits into from
Oct 23, 2024
Merged
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
32 changes: 32 additions & 0 deletions docs/src/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,35 @@ displayed if `Mocking.activate` has been called.
We recommend putting the call to [`Mocking.activate`](@ref activate) in your package's
`test/runtests.jl` file after all of your import statements. The only true requirement is
that you call `Mocking.activate()` before the first [`apply`](@ref) call.

## What if I want to call the un-patched function inside a patch?

Simply call the function without using `@mock` within the patch. For example we can count the number of calls a recursive function does like this:

```julia
function fibonacci(n)
if n <= 1
return n
else
return @mock(fibonacci(n - 1)) + @mock(fibonacci(n - 2))
end
end

calls = Ref(0)
p = @patch function fibonacci(n)
calls[] += 1
return fibonacci(n) # Calls original function
end

apply(p) do
@test @mock(fibonacci(1)) == 1
@test calls[] == 1

calls[] = 0
@test @mock(fibonacci(4)) == 3
@test calls[] == 9
end
```

Note that you can also use `@mock` _inside_ a patch, which can be useful when using
multiple dispatch with patches.
Loading