Last active
June 9, 2021 03:46
-
-
Save Tsugami/3f462761affb40465740eb9ed6a1d568 to your computer and use it in GitHub Desktop.
Example of GenServer with Tests
This file contains 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 Counter do | |
use GenServer | |
def start_link(_) do | |
GenServer.start_link(__MODULE__, 0, name: __MODULE__) | |
end | |
@impl true | |
def init(initial), do: {:ok, initial} | |
@impl true | |
def handle_call(:count, _from, state), do: {:reply, state, state} | |
def handle_call(:increment, _from, state), do: {:reply, state + 1, state + 1} | |
def handle_call(:decrement, _from, state), do: {:reply, state - 1, state - 1} | |
def count, do: GenServer.call(__MODULE__, :count) | |
def increment, do: GenServer.call(__MODULE__, :increment) | |
def decrement, do: GenServer.call(__MODULE__, :decrement) | |
end |
This file contains 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 CounterTest do | |
use ExUnit.Case, async: true | |
setup do | |
start_supervised!(Counter) | |
%{} | |
end | |
test "if Counter loads with initial state of 0" do | |
assert Counter.count() === 0 | |
end | |
test "if Counter.count/0 return the current state" do | |
assert Counter.count() === 0 | |
assert Counter.increment() === 1 | |
assert Counter.count() === 1 | |
end | |
test "if Counter.increment/0 increases state to +1 and return the current state" do | |
assert Counter.count() === 0 | |
assert Counter.increment() === 1 | |
assert Counter.count() === 1 | |
assert Counter.increment() === 2 | |
assert Counter.count() === 2 | |
end | |
test "if Counter.decrement/0 decrements state to -1 and return the current state" do | |
assert Counter.count() === 0 | |
assert Counter.increment() === 1 | |
assert Counter.count() === 1 | |
assert Counter.decrement() === 0 | |
assert Counter.count() === 0 | |
assert Counter.decrement() === -1 | |
assert Counter.count() === -1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment