Dmitry Harnitski
Dmitry Harnitski

Reputation: 6008

How can I run unit tests without calling application callback

My application callback start Supervisor that conflicts with unit tests.

With that callback I am getting something like {:error, {:already_started, #PID<0.258.0>}} when I try to run unit test because my processes are already started.

Can I execute Application callback only for :dev and :prod, keeping :test environment clean of startup code?

I am looking for something like this:

def application do
[
  applications: [:logger],
  mod: {MyApplication, [], only: [:dev, :prod]} 
]

only: [:dev, :prod] - this is missing piece

Upvotes: 1

Views: 330

Answers (2)

Dogbert
Dogbert

Reputation: 222040

I do not know if this is the correct way to handle testing in this case, but here's how you can do what you're asking for:

In mix.exs:

def application do
  rest = if(Mix.env == :test, do: [], else: [mod: {MyApp, []}])
  [applications: [:logger]] ++ rest
end

For the demo below, I added the following to MyApp.start/2:

IO.puts "starting app..."

Demo:

$ MIX_ENV=dev mix
starting app...
$ MIX_ENV=prod mix
starting app...
$ MIX_ENV=test mix # no output

Upvotes: 2

Harrison Lucas
Harrison Lucas

Reputation: 2961

One solution is to kill that process before the test suite runs. For example you could do something like the below:

setup do
  Process.exit(pid, :kill)
end

test "do something..." do
  assert 1 == 1
end

This will ensure that before the test is run, that process is already killed.

Upvotes: 0

Related Questions