Introduction to Writing Properties
Explore the fundamentals of writing properties in property-based testing with PropEr. Understand the differences between stateless and stateful properties, learn the structure of property files, and see how to use default generators to create effective tests. This lesson helps you interpret test results and fix failing cases to improve your testing skills.
We'll cover the following...
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 involve coming up with rules about a program that should always remain true. However, we’ll need to find a way to turn these rules into executable code so that a specific framework (PropEr) can exercise them. We will also need to tell the framework about what kind of inputs it should generate to truly challenge the rules. This is called a generator. Once we combine the encoded rules and the generators, we have a property.
Types of properties
There are two main types of property:
- Stateless properties
- 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 and without major side effects. They are still usable 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, along 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 learn how to fix them.
Structure of properties
All properties share a basic structure. Fancier stateful properties will only add content and special calls, but the core will remain the same. All properties go into files that contain an Erlang (or Elixir) test module and must respect a specific format.
We’ll be looking for the structure we’ll use within these modules to let PropEr know what the rules to test are and let them know how to generate the data it should use to test them. There are three things that we have to understand about the structure of properties:
- File Structure
- Property Structure
- Execution Model