elixirex-unit

ExUnit mock sequence


Is it possible to mock a sequence of return values with ExUnit Mock the same way meck provides this functionality in Erlang?

...
meck:new(my_module),
meck:sequence(my_module, method, 1, [Response1, Response2]),
meck:unload(module),
...

If not, is it possible to successfully combine meck and mock in the same unit test ExUnit Elixir module?


Solution

  • There's no mention of :meck.sequence in mock.ex so I'm guessing this is not supported yet.

    It should be fine to call :meck functions directly as long as it's outside a Mock.with_mock call and you make sure to call :meck.unload/1 after you're done. (And you use async: false, as Mock already requires.) This should be fine even in the same test.

    test "the truth" do
      url = "http://www.google.com"
    
      :meck.new(HTTPoison)
      :meck.sequence(HTTPoison, :get!, 1, [%{body: "foo"}, %{body: "bar"}])
      assert HTTPoison.get!(url).body == "foo"
      assert HTTPoison.get!(url).body == "bar"
      assert HTTPoison.get!(url).body == "bar"
      :meck.unload(HTTPoison)
    
      assert HTTPoison.get!(url).body =~ "HTML"
    
      with_mock HTTPoison, [get!: fn(_url) -> %{body: "baz"} end] do
        assert HTTPoison.get!(url).body == "baz"
      end
    
      assert HTTPoison.get!(url).body =~ "HTML"
    end
    

    Demo:

    $ mix test
    .
    
    Finished in 0.2 seconds
    1 test, 0 failures