Hello Martin! What’s so great about property-based tests?

I’d say it’s that they can surprise both you and your bugs. Every assert you write tests a scenario you anticipated. But the real production bugs? More often than not, they live in combinations nobody thought of.

Ordinary unit tests (example-based testing) are a verification strategy: they protect against regressions in known cases. Absolutely essential. But they don’t search for new bugs, and running them again doesn’t give you any new information.

Property-based testing (PBT) is a completely different kind of testing that can help you find those surprising bugs. Instead of writing specific examples, you describe properties: rules that should always hold. Then hundreds or thousands of random test cases are generated, hunting for the ones that break those rules.

I’ve used it in several live client projects, and it has found bugs we would never have caught with hand-written test cases, including in code we’d been using for a year and believed was stable.

PBT sounds like an unusually effective safety net, yet very few developers use it. Why do you think that is?

When I talk to other developers about PBT or show them the tests we have, they usually think it sounds interesting. But they aren’t truly impressed until they need to change something in complex code and an existing PBT test finds a problem, while also pinpointing exactly which steps are needed to trigger the bug. That’s when they realise this is an exceptional safety net.

So why isn’t it used more widely? These are the three reasons I hear most often:

"I’m not familiar enough with what it is, or whether it would work in my project."

It’s actually not that complicated, and PBT is a very powerful tool in the testing toolbox. I can almost guarantee it can be used in most projects. Otherwise it becomes a bit of a vicious circle: the fewer people who use it in today’s projects, the fewer bring it into tomorrow’s. That’s one of the reasons I’m now coming out as a PBT person and explaining a bit about how to get started and how it works. Good tests are one of our not-so-secret weapons at factor10.

"It feels like a big step to introduce a new testing library and testing method into our codebase."

You might think so, but modern PBT libraries such as fast-check (for JS/TS), Hypothesis (for Python) and CsCheck(for .NET) are easy to integrate with existing test frameworks. You can perfectly well introduce a single PBT test among all your other tests. (Tips on good libraries for the JVM world are very welcome!)

"If the test gets random input, how can I verify that the result is correct?"

This is known as the test oracle problem: the difficulty of determining what correct behaviour is without an answer key. If only you had an all-knowing Trash Heap that delivered the right answer for every situation, generating thousands of tests would be easy. The first two reasons are mostly about getting started. This one is the real hurdle, so let's take a closer look at it.

The question we need to anser is this: With unknown inputs, how can I write a test that checks the output?

With unknown inputs, how can I write a test that checks the output?

I'm glad you asked. In an example-based test, you are the test oracle: you pick the inputs, so you know the right answer. Given 1 and 2, add should return 3. With PBT the inputs are generated, so you can't write down the exact answer in advance. If you've only written example-based tests, this is the hurdle to get past.

The trick is to stop asking for the exact answer and instead ask what must always be true. Getting some experience reframing the problem this way means PBT will feel more natural to you. You can't say what A + B equals for any two random integers, but you can say that adding two positive numbers should never give a result smaller than either of them.

Sometimes your code will contain function pairs that can serve as an oracle: encrypt and decrypt, encode and decode, write and read. Even if you don't know what an encrypted password should look like, you know that decrypting it should give you the original back, so password == decrypt(encrypt(password)). It's a great place to start, but not everything has a reverse. What would the opposite of sending an email be?

Two approaches work much more broadly, and they're the ones I reach for most: comparing against a simpler model and checking that different paths lead to the same result.

1. Compare against a simpler model

Let’s go straight to what may be the most powerful tool we have in PBT: model-based tests. Here are links to the documentation for model-based testing in fast-check (for JS/TS), Hypothesis (for Python) and CsCheck (for .NET.

Suppose the implementation we want to test is a shopping cart where the user can add and remove items. A first model-based test could then use an integer as its model. A model is a simplified representation of the system’s state, and in this case an integer is enough to keep track of the number of items in the cart. We’ve simply created a basic test oracle for ourselves.

The first commands could be adding and removing a quantity of items. Commands are the test events that should affect both the shopping cart and the model. A series of commands is then generated (add(5), add(12), remove(8) and so on), and we let the commands act on both the cart and the model. After each step, we check that they match. In other words, you build up the cart’s state over a series of events, which is one of the reasons these tests are so powerful!

This first simple test might at most verify that you can’t accidentally end up with a negative number of items, but you have to start somewhere. Later, we can extend the model, the commands and the verification in several possible steps:

  • We can distinguish between different items by extending the model to a dictionary (item number => quantity) and having each command also take an item number.
  • We can set a fixed price for all items and verify that the cart’s value matches unit price × number of items.
  • We can set different prices for different items and verify that the value matches.

It’s common to improve the same test gradually over a longer period. Perhaps when you fix a bug, extend the cart’s functionality (say, by adding support for discounts), or when you think of more scenarios you want to cover. My point is that you can start very simply!

2. Check that different paths lead to the same result

Another powerful method is what I call transforming tests. (The more academic name is "metamorphic" testing.)

Suppose we’re writing tests for a shopping cart that now also needs to handle discount codes. A discount code “3FOR2” might mean “3 for the price of 2”, say.

One problem with bringing discounts into the mix is that the test then has to calculate the correct price itself. And there may be several different types of discounts. If these calculations are complicated enough, it’s worth considering whether there’s another way than recreating them in the tests. Because you’re not tempted to reuse the discount algorithm from the production code in your tests, are you? The good news is that we can avoid that mental slip by writing a transforming test for the discount calculation instead.

In general, this type of test is about finding cases where several paths should lead to the same result, or where there’s a logical relationship between input and output. Here are some examples. In the shopping cart case, the value shouldn’t change at all if:

  • you add an item and then remove the same item, or vice versa.
  • you add a discount code and then remove the same discount code, or vice versa.
  • you vary the order in which you add a specific list of items and discount codes to the cart.

We can also expect that:

  • the value should go up (or stay the same) if you add items.
  • the value should go down (or stay the same) if you add discount codes.

This is because neither items nor discounts should be able to have negative effects.

And finally, what's the best way to get started?

My advice if you want to give PBT a try is to start small. Pick a piece of code you already have tests for, write one property-based test next to them and see what it finds. Chances are it’ll be something you didn’t expect. And once that happens, you’re probably a PBT person too!