Testing Pure Functions

Learn how to test pure functions.

Pure functions

A function is pure if every single time you call the function with the same parameters, it returns the 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 can focus on the data going in, the function parameters, and the response. That’s it.

How to test pure functions

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 the setup was only creating the parameters, which have no impact outside of the test.

The one function that we’ve tested so far, SoggyWaffle.WeatherAPI.ResponseParser.parse_response/1, which is shown below (line 12-30), is a pure function.

Get hands-on with 1200+ tech skills courses.