I think you are confusing unit tests with property-based testing in your question.
Unit tests look at a class as if it was a unit of processing in a signal processing chain, such as an amplifier circuit or a guitar effects rack. I think Kent Beck used exactly this metaphor in his work "Test Driven Development: By Example", but right now I don't have a copy of the book to check.
The point is to explain that it is easier to check that a certain filter always takes out high frequencies, than to check if a specific combination of many filters and distortions make you sound exactly like Jimi Hendrix.
Applied to your case, you may want to test in a unit test that a
List class can
add elements as needed. Being strict with TDD philosophy, you should arrange for the
List to already hold a random number of elements before adding to it -- otherwise, a minimal implementation might know the expected total number and just return that.
Property-based testing, on the other hand, checks that a function is mathematically well-defined in the sense that it returns what is expected for the whole domain where it is defined (the definition here is mine, and may be inaccurate). You can get an idea of how this works by reading on QuickCheck and ScalaCheck.
The core concept is that if you pass to the test framework a function that has a typed signature, e.g.
sum(one: Int, another: Int), then the framework generates many tests by traversing all possible variations of the type. In the
Int goes from
Int.MaxValue: the framework picks, say, 100 value pairs and tries to
sum them. For more complex classes, you may need to tell the framework how to create an Arbitrary instance of your class.
Applied to your case, you may want to show that the
length of your
List is always increased by one after an
add operation. Define an Arbitrary List as a List that already holds a random number of items, and define that after an
add this number is increased by 1.
The main benefit of property-based testing is that you get a lot of tests written automatically for you, and you may even control the generation in order to look for edge cases. The property-based test will generate a 100 lists and check that the invariant holds; the unit test would have to be repeated a 100 times in order to give you such a guarantee. However, property-based testing is not a silver bullet, it is just a complement for unit tests in certain situations.