Writing Property Tests with ExUnit

Learn how to write property tests using ExUnit and StreamData.

Exploring ExUnit and StreamData

Elixir makes testing a breeze using its testing framework, ExUnit. ExUnit is a framework for writing unit tests that is built-in to every Elixir project. Every time we create a new project using mix new, Elixir will automatically create a test directory for us and populate it with a skeleton for writing unit tests for our project. ExUnit is already packaged with Elixir, so we don’t need to install any dependencies.

StreamData is an Elixir library for writing property-based tests. Property-based tests test the properties of a function to ensure our code meets some specified properties every time. Property-based tests are especially useful when functions contain randomness because we can write tests that run hundreds of times and ensure the functions meet specified properties and behaviors. For example, if we had a function that generated lists of length 10 of random integers between 1 and 10, we could run the function hundreds of times and ensure that every time it ran, the list it generates contains 10 elements and all of the elements are integers between 1 and 10. StreamData offers utilities for creating streams of data that can be combined with its ExUnitProperties module to write property-based tests.

This lesson will walk us through an example property-based test for Toolbox.Crossover.single_point/2. We can repeat this process with the rest of our functions in our framework.

Adding StreamData to the framework

To get started, first add StreamData to your dependencies, like this:

Get hands-on with 1400+ tech skills courses.