Testing Pure Functions

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Creating Comprehensive Test Coverage | TOC | Refactoring Toward Pure Functions 👉

The simplest code to test is a pure function.[12] A function is “pure” if, every single time you call the function with the same parameters, it returns the exact same answer and if it has no side effects. If a dependency can change the result, the function is not pure. When testing a pure function, the test is able to focus on the data going in — the function parameters — and the response. That’s it.

With pure functions, the only setup we need is to prepare the data for the parameters. The exercise step for the test is a function call, passing the input parameters. The verify stage is just assertions on the response, and only the response. There is no teardown because setup was only creating the parameters, which have no impact outside of the test. Let’s take a look at some examples of tests on a pure function.

The one function that we’ve tested so far, SoggyWaffle.WeatherAPI.ResponseParser.parse_response/1, is a pure function. Our tests never had to worry about side effects and they consistently get the same response from the code under test, no matter how many times they’re run.

While testing pure functions is simple, most applications can’t be comprised entirely of pure functions, so we have to look at two strategies for testing code that has state: moving logic into pure…

--

--

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.