Skip to content

Commit

Permalink
Always overwrite the stub when merging new expects or stubs (dashbitc…
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyvanriet authored and José Valim committed Aug 18, 2019
1 parent 5e19b5b commit 2667b2d
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
5 changes: 5 additions & 0 deletions lib/mox.ex
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,11 @@ defmodule Mox do
`expect/4` can also be invoked multiple times for the same
name/arity, allowing you to give different behaviours on each
invocation.
When `expect/4` is invoked, any previously declared `stub` for the same `name` and arity will
be removed. This ensures that `expect` will fail if the function is called more than `n` times.
If a `stub/3` is invoked **after** `expect/4` for the same `name` and arity, the stub will be
used after all expectations are fulfilled.
"""
def expect(mock, name, n \\ 1, code)
when is_atom(mock) and is_atom(name) and is_integer(n) and n >= 0 and is_function(code) do
Expand Down
4 changes: 2 additions & 2 deletions lib/mox/server.ex
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ defmodule Mox.Server do
end
end

defp merge_expectation({current_n, current_calls, current_stub}, {n, calls, stub}) do
{current_n + n, current_calls ++ calls, stub || current_stub}
defp merge_expectation({current_n, current_calls, _current_stub}, {n, calls, stub}) do
{current_n + n, current_calls ++ calls, stub}
end
end
15 changes: 13 additions & 2 deletions test/mox_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,17 @@ defmodule MoxTest do
end
end

test "raises if all expectations are consumed, even when a stub is defined" do
stub(CalcMock, :add, fn _, _ -> :stub end)

expect(CalcMock, :add, 1, fn _, _ -> :expected end)
assert CalcMock.add(2, 3) == :expected

assert_raise Mox.UnexpectedCallError, fn ->
CalcMock.add(2, 3)
end
end

test "raises if you try to add expectations from non global process" do
set_mox_global()

Expand Down Expand Up @@ -485,11 +496,11 @@ defmodule MoxTest do
end)
end

test "invokes stub after expectations are fulfilled" do
test "a stub declared after an expect is invoked after all expectations are fulfilled" do
in_all_modes(fn ->
CalcMock
|> stub(:add, fn _x, _y -> :stub end)
|> expect(:add, 2, fn _, _ -> :expected end)
|> stub(:add, fn _x, _y -> :stub end)

assert CalcMock.add(1, 1) == :expected
assert CalcMock.add(1, 1) == :expected
Expand Down

0 comments on commit 2667b2d

Please sign in to comment.