Testing GenServers

Hello folks! First time poster here, really happy to participate.

I’m using Jose’s Periodically module for a project and I was wondering how I’d unit test something like that. Here’s what I have in mind:

defmodule MyApp.PeriodicTest do
  use ExUnit.Case, async: true

  test "Basic Behaviour" do
    caller = self
    args = %{interval: 100, work: fn ->
        send(caller, "done")
    end, id: self()}
    GenServer.start_link(PollingToSocket.Periodically, args)

    assert_receive("done", 150)

  end
end

Is there a better approach I can use? I’m still a beginner, so I’m wondering if there’s a more obvious answer I may be missing

3 Likes

hi, you can use start_supervised for handling better the GenServer with ExUnit,
also can try passing as argument the schedule_worker (strategy function) like a parameter so you can make control the steps of execution.

 scheduler_worker_iterator = fn -> end # do nothing

 {:ok, pid} = start_supervised!({PollingToSocket.Periodically, [scheduler_worker: scheduler_worker_iterator, ... rest args])

 # now we can control iteration
for _ <- (1..10) do  
send pid, :work
end 

 for _ <- (1..10) do
  assert_receive 'done', 150
 end
2 Likes