Last active
May 16, 2019 20:01
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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