Warning when using mox

I am using Mox in phoenix and the tests successfully pass. However, I get the following warning:

warning: function MyApp.ServiceMock.function_name/2 is undefined (module MyApp.ServiceMock is not available) lib/myapp_web/controllers/service_controller.ex:26

The controller properly picks up ServiceMock in test environment, runs it and the tests pass. However, I wonder why I am getting this warning that function is undefined and ServiceMock is not available. Anyone else faced this issue.

Thanks,

RKC

I am getting this error when:

	defmodule MyApp.UserController do
	use MyAppWeb, :controller

	@external_service Application.get_env(:myapp, :external_service) # this line causes warning

	def register(conn, params) do

		with {:ok, result} <- @external_service.validate(params) do

I do not get error when I do the following:

defmodule MyApp.UserController do
	use MyAppWeb, :controller

	def register(conn, params) do

		with {:ok, result} <- Application.get_env(:myapp, :external_service).validate(params) do # now the warning disappears

I wonder what I am doing wrong?

Thanks,

RKC

1 Like

Hello there!

I believe that the warning will happen in the first scenario because the module atribute @external_service will be swapped by the actual MockExternalService module during compilation time, and the Mox mock module will only be created during the tests execution.

In the second scenario, the compiler won’t even have a chance to check whether the module exists or not.

You are probably fine anyway.

I personally use the first way of doing it, because I’d rather have the warnings instead of having a function call every time my app has to resolve the module name.

Cheers!

1 Like

Hi, there are section (maybe new) about warnings
Mox — Mox v1.1.0 :

If the mock needs to be available during the project compilation, for instance because you get undefined function warnings, then instead of defining the mock in your test_helper.exs, you should instead define it under test/support/mocks.ex

14 Likes