jjh42 / mock

Mocking library for Elixir language

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is it possible to mock the same function more than once ?

crisefd opened this issue · comments

I have a module named Randomise and in it, I have a function integer_random . The function is called multiple times inside another function (the one that is being tested). Let's say that during the test the Randomise.integer_random/1 function is called 6 times, can I mock the same function six times ? And if not, is there a workaround I could use ?

As long as the mock is in place, the mocked function can be called as many times as you like. Maybe I don't quite understand your issue.

If the mocked function is gonna be called 6 times, I want to return 6 different values.

You can either create 6 different mocks, or just make the mocked function count it

I think I understand what @crisefd is trying to achieve

If we have the following module:

defmodule Foo do
  def foo1(in1), do: :ok
end

I would expect the following test to pass:

defmodule FooTest do
  use ExUnit.Case, async: false
  import Mock

  test_with_mock "TestFoo", Foo, [],
    [
      foo1: fn("1") -> "foo1-1" end,
      foo1: fn("2") -> "foo1-2" end,
      foo1: fn(_) -> "foo1-default" end
    ]
  do
    assert "foo1-1" == Foo.foo1("1")
    assert "foo1-2" == Foo.foo1("2")
    assert "foo1-default" == Foo.foo1("3")
  end
end

However, all my calls to Foo.foo1 return "foo1-default".

In fact, if I remove foo1: fn(_) -> "foo1-default" end, I get the following error:

(FunctionClauseError) no function clause matching in anonymous fn/1 in FooTest.test TestFoo/1

That is correct, I think that mocking multiple times does not work because it only taskes into account the last one

  test_with_mock "TestFoo", Foo, [], [foo1: fn
    "1" -> "foo1-1"
    "2" -> "foo1-2"
    _ -> "foo1-default"
  end]

@karlseguin Thanks for the quick and simple solution!

@crisefd I think this solution addresses what we need, so do you think we can go ahead and close out this issue?

Yeah, thanks. We can now close this issue