I see a bit of a growing meme that the red step in Test Driven Development‘s (TDD) red-green-refactor cycle means that your test will not compile because there is no code to implement it yet.
The red step is necessary because of the possibility that your test itself has an error in it. We face something of a chicken-and egg problem with a test. We understand that we should write a test before writing code, but we cannot write a test before writing our test code with hitting a recursion issue. So we say that we write a test before writing any production code. However, our test code is a valuable as production code, so we need to prove its correctness too.
How do we do that?
By making sure that when our test fails as expected. The four phase test model (setup, exercise, verify, teardown) and the arrange-act-assert pattern all say the same thing – put the system is a known state, exercise the change we are testing, and verify the new state of the application. So by stubbing the operation under test to put the application into an invalid state after it is called, we cann prove that our test will fail. This check of the test itself makes the bar go red in our Test Runner. Hence the ‘red’ name for this step.
A corollary to this is that you should author your tests so that you can simply prove success-failure of the test. Tests that have conditional logic for example are bad tests – you should know what your test is doing. So getting a red step to fail easily is generally also a good marker that we are indeed testing a unit. If getting a red is really hard, there is probably an architectural smell.
There is a temptation to skip the red phase and go straight to getting to green. The risk here is that you have a false positive – your test would always pass. Kent Beck talks about the model of driving in a different gear when doing TDD. Skipping the red phase can work if you feel able to drive in a high gear – the road ahead is straight, wide open and flat and you want to eat miles as fast as you can. However as soon as you hit a steep downhill gradient, bends or traffic, you need to shift down again. Usually the indicator here would be that you find your tests would probably always have succeeded when you get to green. However, having regularly encountered mistakes in my tests using the red step I would avoid driving in high gear without thinking about it.
But remember red is not ‘fails to compile’ it is ‘test fails as expected’.