Randomness and Property-Based Testing

Get to know the benefits of randomness in property-based testing

Adding randomness to tests

We can solve some of the problems that example-based tests suffer from by introducing a bit of chaos in our tests. Using randomness to generate inputs will allow us to test a wider range of inputs against our code and potentially create inputs that trigger edge cases.

In our sorting example, what we really want to test is that the output of Enum.sort/1 is a sorted version of the input. For any random input, we can think of a few properties that the output will always retain. For example,

  1. The output list always has the same length as the input list.
  2. Another property is that the output list is always sorted, which is something that we can check in a pretty straightforward way by checking that each element is smaller than or equal to the following one.

Get hands-on with 1400+ tech skills courses.