How to stop Supervisors starting GenServer during Exunit tests?

It seems that the easiest way to solve it is just to start your GenServer under a different name, using the :name option? Though if your GenServer functions depend on a hardcoded :name such as __MODULE__ it would indeed making testing harder.

e.g. instead of writing

  def start_link(_) do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

write

  def start_link(opts) do
    GenServer.start_link(__MODULE__, :ok, opts)
  end

and then the child spec:

      %{
        id: MyApp.MyGenServer,
        start: {MyApp.MyGenserver, :start_link, [[name: MyApp.MyGenServer]]}
      }

then in your test you can give a different name, e.g.

  setup context do
    _ = start_supervised!({MyApp.MyGenserver, name: context.test})
    %{producer: context.test}
  end
1 Like