Property-based Testing in a nutshell.

Gunar Gessner
Mar 6 · 2 min read
Photo by Andrew Wulf on Unsplash

Property-based Testing in a nutshell.

Hi! Welcome to part one of my series on mental models. Click here for other parts.

Let’s say we have ourselves a sorting function called mySort ,

Standardized testing would ask you to come up with some values to be tested,

whereas Property-based Testing asks you to declare the schema of the data,

Property-based Testing example (pseudo-code).

and the testing framework takes care of generating the test-data for you.

The actual code is quite similar. The only difference being that in a standardized test you provide values, whereas for property-based tests you provide arbitraries* (i.e. types), and test-data is generated for you.

Standardized testing has values as first-class citizens, whereas Property-based Testing has types in its stead*.

* Paraphrasing this tweet from Lorin Hochstein.

Side-note: Most of the time you’ll either use the predefined arbitraries or you’ll derive from integer, e.g. nat = integer().filter(x => x > 0) .

Talk is cheap, show me the code.

I’m going to use this example from fast-check—a JavaScript implementation.

Let’s take our sorting function again, and say we want to be able to test two properties:

  1. Whether the array that is returned is of the same size as the array that’s been passed to the function (i.e. the function argument).
  2. Whether all items in the returned array have a value that is greater than the value of the item preceding them (i.e. a[n] > a[n — 1]).

And now as code:

Verdict: Add it to your toolbelt.

Property-based Testing is a relatively simple concept that compared to standardized tests may yield superior confidence at reduced costs.

Invisible: Reports


Gunar Gessner

Written by

Software Engineer —

Invisible: Reports


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade