Introduction to Writing Properties

Get started with properties and a better understanding of how they work to write them easily.

Introduction

Property-based testing requires us to approach testing differently from what we’re used to. As we’ve seen earlier, the core of properties is coming up with rules about a program that should always remain true. That’s the hard part. But just having that will not be enough. We’ll need to find a way to turn these rules into executable code so that a specific framework (PropEr in our case) can exercise them. We will also need to tell the framework about what kind of inputs it should generate to truly challenge the rules, something we call a generator. Once we take the rules encoded as code, the generators, and then put them together through the framework, we have a property.

Types of properties

Properties come in multiple varieties, but the two main categories of properties are:

  1. Stateless properties
  2. Stateful properties

In traditional example-based testing, it’s usually a good idea to start with simple unit tests. In property-based testing, stateless properties are their equivalent. Stateless properties are a great fit to validate isolated, stateless components without major side effects. They are still used for more complex stateful integration and system tests, but stateful properties are more appropriate for those use cases.

The properties we’ve seen and discussed in the previous chapter were all stateless, albeit a bit abstract. In this chapter, we’ll make everything concrete and see how stateless properties are structured so that we can read and understand them. We’ll also see what data generators are offered out of the box by PropEr, with some ways of composing them together. Finally, we’ll run some more properties. This will allow us to figure out how to read the results of failing test cases and see how to fix them.

Get hands-on with 1200+ tech skills courses.