Property-based testing
Unit tests are a tremendously useful tool to verify the robustness of our program. However, as we have seen in the earlier examples, we are always checking against single cases, and, even when automatically generating parameters for our tests, it is always difficult to be sure that there are no edge cases we may be missing.
The solution is not to test against the results of a function but against properties. This way, we can feed any value to the function, and verify that the properties are always fulfilled. We can also think of the properties as the requirements of the application. For example, we may want to verify that our add function, given earlier, fulfills the following three properties of addition:
- Commutative property:
add x y
should be the same asadd y x
- Associative property:
add x y |> add z
should be the same asadd y z |> add x
- Identity property:
add x 0
should be the same asx
Thanks to F#'s expressiveness, it is really easy to write these conditions...