Skip to content

Instantly share code, notes, and snippets.

@jerel
Last active May 16, 2019 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerel/b8d78995ffb7820680ab4cb7b1bdd827 to your computer and use it in GitHub Desktop.
Save jerel/b8d78995ffb7820680ab4cb7b1bdd827 to your computer and use it in GitHub Desktop.
Test code that a GenServer calls by injecting a mock client that sends a message to a named test process
defmodule Example.Server do
use GenServer
defmodule Data do
defstruct client: Example.Client
end
def init(%{client: client}), do: {:ok, %Data{client: client}, 500}
def init(_), do: {:ok, %Data{}, 500}
def handle_info(:timeout, %Data{client: client} = state) do
client.request(nil)
{:noreply, state}
end
end
defmodule Example.Mock.Client do
def request(message) do
send(Example.TestReceiver, {:request, message})
:ok
end
end
test "test that the client is called after 500 ms" do
Process.register(self(), Example.TestReceiver)
assert {:ok, _pid} = Example.Server.start_link(%{client: Example.Mock.Client})
assert_receive({:request, ^message}, 510)
end
test "get notified when the server shuts down" do
Process.flag(:trap_exit, true)
assert {:ok, pid} = Example.Server.start_link(%{client: Example.Mock.Client})
assert_receive({:EXIT, ^pid, :normal})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment