dashbitco / mox

Mocks and explicit contracts in Elixir
1.35k stars 77 forks source link

Mox require `Application.ensure_started(:mox)` at test_helper.exs #92

Closed calvin-kargo closed 4 years ago

calvin-kargo commented 4 years ago

Hi all, i was trying out mocking with Mox, (at version 0.5.2), but somehow it throw Mox.Server is not alive error like

     ** (exit) exited in: GenServer.call(Mox.Server, {:add_expectation, #PID<0.250.0>, {CoronaNews.GatewayMock, :fetch_data_for_country, 1}, {1, [#Function<1.87899743/1 in CoronaNewsTest."test CoronaNews text_news_for/1 on Gateway Success"/1>], nil}}, 30000)
         ** (EXIT) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started

the test code was like

# at test/test_helper.exs
Application.put_env(:corona_news, :gateway, CoronaNews.GatewayMock)
Mox.defmock(CoronaNews.GatewayMock, for: CoronaNews.Gateway.Behaviour)
ExUnit.start()

# at corona_news_test.exs
defmodule CoronaNewsTest do
  use ExUnit.Case
  import Mox

  describe "CoronaNews" do
    test "text_news_for/1 on Gateway Success" do
      CoronaNews.GatewayMock
      |> expect(:fetch_data_for_country, 1, fn country ->
        assert country == CoronaNews.Country.indonesia()
        {:ok, %{
          total_case: 6,
          total_recovered: 3,
          new_case: 1,
          latest_update: ~U[2020-05-02 13:37:37Z]
        }}
      end)

      assert """
      Total Case: 6
      Total Recovered: 3
      New Case: 1
      Latest Update: 2020-05-02 13:37:37Z
      """ == CoronaNews.text_news_for(CoronaNews.Country.indonesia())
    end

    test "text_news_for/1 on Gateway Failed" do
      CoronaNews.GatewayMock
      |> expect(:fetch_data_for_country, 1, fn country ->
        assert country == CoronaNews.Country.indonesia()
        {:error, "Error due to Mock"}
      end)

      assert """
      Failed fetching data
      Error: \"Error due to Mock\"
      """ == CoronaNews.text_news_for(CoronaNews.Country.indonesia())
    end
  end
end

only by adding Application.ensure_started(:mox) at test_helper.exs i resolve the error.

I was not certain why this happen, and Documentation at Hex doesn't mention this at all.

iex -v

Erlang/OTP 22 [erts-10.6.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe] IEx 1.9.4 (compiled with Erlang/OTP 21)

calvin-kargo commented 4 years ago

It is actually covered on https://github.com/dashbitco/mox readme page, closing this issue.