3. Testing the GenServer - abarr/remote GitHub Wiki
Testing a GenServer
can be tricky, so I wanted to add a handle_call
purely for getting a test working before implementing the next set of requirements.
Setup
I added a the following function to the GenServer
"/lib/remote/users/user_server.ex"
defmodule Remote.Users.UserServer do
@moduledoc false
use GenServer
...
def get_state(server \\ __MODULE__) do
GenServer.call(server, {:get_state})
end
...
Then tested it using iex -S mix
$ iex -S mix
Erlang/OTP 24 [erts-12.0] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1]
Compiling 1 file (.ex)
Interactive Elixir (1.13.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Remote.Users.UserServer.get_state()
%{max_number: 31, timestamp: nil}
iex(2)>
Writing a Test
I added the following test file.
"/test/remote/user_server_test.exs"
defmodule Remote.UserServerTest do
use ExUnit.Case, async: true
setup do
user_server = start_supervised!({Remote.Users.UserServer, name: __MODULE__})
%{user_server: user_server}
end
test "get state", %{user_server: user_server} do
assert %{max_number: _num, timestamp: nil} = Remote.Users.UserServer.get_state(user_server)
end
end
Using the start_supervised!
option in the setup
call back allows me to create a GenServer
and pass it to the call to test that the code is working.
Running the tests I see that is working.
$ mix test
...
Finished in 0.03 seconds (0.03s async, 0.00s sync)
3 tests, 0 failures
two of the tests are generated tests for view.