3 ms·
There is a reason for the "return 9" trick. The point is to force you to write a test that breaks the previous test. In this style of TDD you need to always
by mikekchar 8y ago
There is a reason for the "return 9" trick. The point is to force you to write a test that breaks the previous test. In this style of TDD you need to always be working from "red" (in the red/green/refactor cycle).
If your test is "add(4, 5)" and you implement add with "a + b", there is no failing test you can add. However, there are many classes of potential failures. For example, what if "a" or "b" is zero? What if one of them is negative? Even potentially, what about real numbers, etc. If you write your first failing test and then implement it with the entire solution, then you often stop with a single test that doesn't cover the edge cases you care about.
However, the real problem is explaining that style of TDD with such a simple function. I would never use a test first style for "add" unless there were some reason to do so (for example, there was some reason to assume that 0 wouldn't work). The "return the answer" trick is really useful when you have a function that has a very complex set of return values. You pick some arbitrary value to test against so that when you are working on the solution, you can see if you've broken then "happy path" test.
The "return the answer" bit is not even necessary, but it's handy to ensure that your test harness is working properly. I've often seen people do a "green-green-refactor" style of testing and write hundreds of lines of code only to realise that their tests weren't even running and the code doesn't work at all. It's 30 seconds of, "Can I write a test that makes the tests go red?", "Can I make the tests go green?" OK, let's begin.