Skip to content

Commit

Permalink
Make stub_with work with skip_optional_callbacks (#96)
Browse files Browse the repository at this point in the history
  • Loading branch information
flurin authored Jul 9, 2020
1 parent d4fbb04 commit 4dd4c9b
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/mox.ex
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,8 @@ defmodule Mox do
end

for behaviour <- behaviours,
{fun, arity} <- behaviour.behaviour_info(:callbacks) do
{fun, arity} <- behaviour.behaviour_info(:callbacks),
function_exported?(mock, fun, arity) do
stub(mock, fun, :erlang.make_fun(module, fun, arity))
end

Expand Down
33 changes: 33 additions & 0 deletions test/mox_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,16 @@ defmodule MoxTest do
def exponent(x, y), do: :math.pow(x, y)
end

defmodule SciCalcFullImplementation do
@behaviour Calculator
def add(x, y), do: x + y
def mult(x, y), do: x * y

@behaviour ScientificCalculator
def exponent(x, y), do: :math.pow(x, y)
def sin(x), do: :math.sin(x)
end

test "can override stubs" do
in_all_modes(fn ->
stub_with(CalcMock, CalcImplementation)
Expand All @@ -603,6 +613,29 @@ defmodule MoxTest do
end)
end

test "stubs functions which are optional callbacks" do
in_all_modes(fn ->
stub_with(SciCalcMock, SciCalcFullImplementation)
assert SciCalcMock.add(1, 2) == 3
assert SciCalcMock.mult(3, 4) == 12
assert SciCalcMock.exponent(2, 10) == 1024
assert SciCalcMock.sin(0) == 0.0
end)
end

test "skips undefined functions which are optional callbacks" do
in_all_modes(fn ->
stub_with(SciCalcMockWithoutOptional, SciCalcImplementation)
assert SciCalcMockWithoutOptional.add(1, 2) == 3
assert SciCalcMockWithoutOptional.mult(3, 4) == 12
assert SciCalcMockWithoutOptional.exponent(2, 10) == 1024

assert_raise UndefinedFunctionError, fn ->
SciCalcMockWithoutOptional.sin(1)
end
end)
end

test "Leaves behaviours not implemented by the module un-stubbed" do
in_all_modes(fn ->
stub_with(SciCalcMock, CalcImplementation)
Expand Down
1 change: 1 addition & 0 deletions test/support/mocks.ex
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
Mox.defmock(CalcMock, for: Calculator)
Mox.defmock(SciCalcMock, for: [Calculator, ScientificCalculator])
Mox.defmock(SciCalcMockWithoutOptional, for: [Calculator, ScientificCalculator], skip_optional_callbacks: true)

Mox.defmock(MyMockWithoutModuledoc, for: Calculator)
Mox.defmock(MyMockWithFalseModuledoc, for: Calculator, moduledoc: false)
Expand Down

0 comments on commit 4dd4c9b

Please sign in to comment.