Property-based Testing

Learn about applying property-based testing, and familiarize yourself with different tools.

Overview

Although theoretically not limited to FP, property-based testing is popular within the FP community and largely unknown outside. The QuickCheck library, the original library for this sort of testing, was written in Haskell and then ported to several other languages. On the other hand, unit testing generally uses the same values to verify that the code is working. Property-based testing generates a large number of random values with which to validate any code. This means that our code is tested against a broad range of values, not the few we carefully select. This is useful when our functions must obey certain mathematical properties. When it comes to business code, however, the random nature of the values might limit its usefulness.

Years ago, our team used a Java library called RandomBeans to automatically fill in fields of Java Objects, minimizing test setup. The difference lies in the goals. RandomBeans tries to minimize setup and repetitive work, whereas property-based testing is more interested in verifying laws.

Let’s look at an example. We have a function called product, which multiplies the values we give as parameters:

Get hands-on with 1200+ tech skills courses.