If two implementations pass every test I have, but one relies on a fragile assumption, how can I tell the difference? Is there a small exercise that makes this clear?
How can two programs pass the same tests when one is wrong?
Answers
Try writing two functions that return the largest number in a nonempty list. One checks every element. The other just returns the first element. Both pass if your tests happen to put the largest number first.
Now try a single element, a largest number at the end, negative numbers and duplicate values. Decide separately what the function should do with an empty list. Each case challenges a different assumption in the implementation or specification.
Reply to this answer
First nail down what correct means. If the only requirement is the returned value, and two programs return the right value for every allowed input, you can't call one wrong just because its algorithm looks strange.
But output may not be the whole contract. Side effects, errors, performance limits and behavior under different execution orders can matter too. A finite test suite usually checks only a small part of that contract.
Reply to this answer
Property-based testing is a nice next step. For a sort function, check that the result is ordered and has exactly the same elements, including duplicate counts, as the input. Then generate lots of lists rather than relying only on a few handpicked examples.
Empty lists, repeated values and already sorted or reverse-sorted lists are good cases to include. Passing generated tests still isn't a proof, but it can expose assumptions you didn't think to test directly.
Reply to this answer
Don't just look at inputs and outputs. Read the implementation for assumptions about execution order, initialized values and shared state. A test might pass repeatedly on one setup while a different scheduling order exposes a bug.
Logging and debugging can help investigate failures that are hard to reproduce. Once you understand one, add a regression test for it where practical.
Reply to this answer
More tests give you more evidence, not a guarantee. For a small finite input domain, exhaustive testing may be possible under the conditions you test. For larger domains, code review and reasoning about the algorithm can complement tests that sample representative and boundary cases.
Reply to this answer
Add your answer
Answers are reviewed before publication.
b.628!ferryclip:
That also makes a useful code review exercise. Ask someone to explain why the result must be at least as large as every element, not just show that a few examples pass.