Table-Driven Property Checking
Learn how to write table-driven property-based tests using ScalaTest.
Property-based tests
There are two main categories of property-based tests:
Table-driven
Generator-driven
We’ve already spent a lot of time on generator-driven tests, in which the input is automatically generated (and possibly filtered) to ensure maximum edge cases are covered. Table-driven tests are a kind of middle ground between generator-driven and example-based tests. As we’ll see in this lesson, they still let us formulate properties over our code, but they also let us choose the actual input using a testing table.
Testing tables are just tables with as many columns as inputs for the unit under test. For example, if we’re testing a stand-alone pure function, we’d have as many columns as the number of parameters of the function itself and as many rows as the number of scenarios we want to test.
Testing Table for a Counter
Initial value | Operation |
0 | +1 |
MAX_INT | +1 |
MIN_INT | -1 |
0 | -1 |
Table-driven property checking in ScalaTest
ScalaTest supports out-of-the-box, table-driven test cases by mixing in the TableDrivenPropertyChecks
trait, allowing us to use tables with up to 22 columns. This limit has a long history in Scala. Initially, case classes were not allowed to have more than 22 members. Similarly, tuples were not allowed to have more than 22 members, and functions were not allowed to have more than 22 parameters.
Scala 2.11 dropped the limitation for case classes, and Scala 3 dropped it for functions and tuples. However, ScalaTest still defines a dedicated ...