Issue with Mox

So I have some code that I am trying to test using Mox library from Jose Valim.

I am trying to test one of gen server methods that start an Task with the correct calls. I was trying to use Mox to that the end Task actually executed does not do anything but at least has the correct contract setup.

Unfortunately, I am unable to make it work unless I set the set_mox_global because looks like I need to allow the spawn process to do something (but I don t have the pid of the task… But when I turn it on, it seems to turn it on for everything in my test suite

here is the code I am trying to test

defmod MyMod do
  def create_task(arg1, arg2) do
    mod = Application.get_env(:my_app, :my_var , MyMod)
    Task.start(mod, :run, [arg1, arg2])
  end
end

And here what my test look like

test "It is called 2 times" do
      MyMock
      |> expect(:run, 2, fn(arg1, arg2) ->
          []
         end)

       MyMod.create_task("hello", "world")
end

I get the following message

cannot add expectations/stubs to MyMock in the current process (#PID<0.631.0>) because Mox is in global mode and the global process is #PID<0.604.0>. Only the process that set Mox to global can set expectations/stubs in global mode

How do you guys go about testing Async Task and Mocking stubbing the actual Module being executed?

4 Likes