Think about the last time you wrote unit tests (which hopefully is pretty recent). You had to come up with the happy-path, the tragic-path, and those hard-to-find edge cases. Since we are not infallible human beings, we tend to miss things more often than not. We miss an edge case here, forget about handling an error there, and discover our omissions during production.
Property-based testing totally flips the notion of unit testing on its head. Instead of writing specific examples of a test, you would write a property instead. A property, in this context, signifies a condition that would hold for all inputs that you define.
An example here is certainly helpful, if not required. Say you want to test a function that reverses an array. What could be some useful properties? Well, I can think of the following:
- The first element of the array becomes the last element
- The length of the array remains the same before and after reversing
- Reversing the array twice will give back the original array
You could probably come up with a few more. With a property-based testing tool, you could express the above as code and tell it to generate hundreds or even thousands of test cases with randomly generated arrays.
A cool feature of many property-based testing tools is shrinking. This means that the tool, to the best of its ability, will find the smallest input that causes the property to be unsatisfied.
Continue reading %The How and Why of Property-Based Testing in Ruby%
by Benjamin Tan Wei Hao via SitePoint
No comments:
Post a Comment