Mock v0.1.3 Mock

Mock modules for testing purposes. Usually inside a unit test.

Please see the README file on github for a tutorial

Example

defmodule MyTest do
  use ExUnit.Case
  import Mock

  test "get" do
    with_mock HTTPotion,
        [get: fn("http://example.com", _headers) ->
                HTTPotion.Response.new(status_code: 200,
                    body: "hello") end] do
      # Code which calls HTTPotion.get
      # Check that the call was made as we expected
      assert called HTTPotion.get("http://example.com", :_)
    end
  end
end

Summary

Macros

Use inside a with_mock block to determine whether a mocked function was called as expected

Shortcut to avoid multiple blocks when a test requires a single mock

Shortcut to avoid multiple blocks when a test requires a single mock. Accepts a context argument enabling information to be shared between callbacks and the test

Mock up mock_module with functions specified as a keyword list of function_name:implementation mocks for the duration of test

Macros

called(arg)

Use inside a with_mock block to determine whether a mocked function was called as expected.

Example

assert called HTTPotion.get("http://example.com")
test_with_mock(test_name, mock_module, opts \\ [], mocks, test_block)

Shortcut to avoid multiple blocks when a test requires a single mock.

For full description see with_mock.

Example

test_with_mock "test_name", HTTPotion,
  [get: fn(_url) -> "<html></html>" end] do
  HTTPotion.get("http://example.com")
  assert called HTTPotion.get("http://example.com")
end
test_with_mock(test_name, context, mock_module, opts, mocks, test_block)

Shortcut to avoid multiple blocks when a test requires a single mock. Accepts a context argument enabling information to be shared between callbacks and the test.

For full description see with_mock.

Example

setup do
  doc = "<html></html>"
  {:ok, doc: doc}
end

test_with_mock "test_with_mock with context", %{doc: doc}, HTTPotion, [],
  [get: fn(_url) -> doc end] do

  HTTPotion.get("http://example.com")
  assert called HTTPotion.get("http://example.com")
end
with_mock(mock_module, opts \\ [], mocks, list)

Mock up mock_module with functions specified as a keyword list of function_name:implementation mocks for the duration of test.

opts List of optional arguments passed to meck. :passthrough will passthrough arguments to the original module.

Example

with_mock(HTTPotion, [get: fn("http://example.com") ->
     "<html></html>" end] do
   # Tests that make the expected call
   assert called HTTPotion.get("http://example.com")
end