🧪 Why property-based testing?
At Promyze, we’re convinced that methodologies such as Test-Driven Development (TDD) can really improve the quality of our code. But developers need relevant inputs to ensure our code answers a business requirement. Behavior-Driven Development or Example Mapping sessions help to generate concrete examples of the behavior of a feature. This clearly brings value for developers and allows them to start writing tests and business code.
However, our tests usually cover a restricted range of inputs that come from our examples. We assume they are representative enough for our tests. But what if we want to test edge cases? Or if we’re not sure that our test is representative?
This is where property-based testing comes in. This post is a short intro to this concept.
❓ What is Property-Based Testing (PBT)?
Property-based testing aims to identify and test invariants: predicates that should be true, whatever the input data are. An invariant is a business rule that can be written as a predicate.
A PBT framework will generate random input data and check if the invariant is valid. If one single execution fails, this means the code under test may have some defects in its implementation. But the PBT framework will give you the input data, meaning you can reproduce the problem.
PBT is not something new, the first research studies on that topic are from 1994, from Fink & Levitt.
🎓 Illustration with a test case
Our platform Promyze is designed for best coding practices sharing. Users can merge two practices if they have the same intention. Each practice can have zero, one, or multiple categories. During a merge, categories of both practices should be merged into the target practice.
Here is a simple implementation of this business rule (the mergePractice method) and a unit test written in JS with Mocha and Chai. For simplicity, the code is written in the same file.
Social media