Testing a GenServer

Testing Elixir — by Andrea Leopardi, Jeffrey Matthias (31 / 80)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 3 Testing OTP | TOC | Controlling the Life Cycle of OTP Processes in Tests 👉

Let’s refresh our memory: a GenServer is a process that holds state and optionally provides an interface to read or update that state. OTP abstracts all of the common parts of a GenServer, like spawning the process, having a receive loop, and sending messages. What’s left to the user is to implement callbacks that implement code that’s specific to a particular GenServer.

We’ll see how we can make use of a GenServer in the Soggy Waffle application, but we’d like to start off with a self-contained example. It’s going to make things easier when illustrating some concepts. We’ll use a GenServer that provides a simple rolling average of the last N numeric measurements given to it. We can start with a simple implementation by looking at the public API exposed by the GenServer:

testing_otp/rolling_average/overloaded_genserver.ex

​ ​def​ start_link(max_measurements) ​do​
​ GenServer.start_link(__MODULE__, max_measurements)
​ ​end​

​ ​def​ add_element(pid, element) ​do​
​ GenServer.cast(pid, {​:add_element​, element})
​ ​end​

​ ​def​ average(pid) ​do​
​ GenServer.call(pid, ​:average​)
​ ​end​

We have a function to start the GenServer, a function to store a new element in the GenServer, and a function to get the average of the elements that the GenServer…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.