“Why does it matter if I write the test first or not?

Someone on the internet mentioned that if your organization values test, it doesn’t matter if you write them before the code is written or after the code is written.

I respectfully disagree.

Test Driven Development is a discipline I’ve talked about before. Briefly, you write the test first; only write enough code to pass that single test; and then you refactor the code to clear out any duplication moving forward (I particularly like the Rule of Three in deciding whether to refactor).

Unit Testing is somewhat the opposite. You have the code already written, and someone, be it yourself or a pointy-haired boss, says, “That should be under test!” So you write the test(s) that cover the code’s responsibilities, and you call it a day.

Non-obviously, they have different — and sometimes opposite effects on your team and codebase.

Unit tests incur pain to write: Systems that are created without testability in mind are harder to write tests for than systems that are written to be tested. This is a truism, and generally accurate.

TDD requires discipline to write: Ensuring each piece of behavior is specified in a test first is an uncommon way for a builder to think about building.

Unit tests are brittle, since they are written around the scar tissue of the system, they’re affected by structural changes in the system. TDD style development is not.

TDD requires a change to how you think about designing software. Unit tests do not.

I could go on and on, but these attributes affect the entire system and the people who depend on it; and are not merely cosmetic choices.

Leave a Reply