Site Tools


test-driven-development

Test-driven development

Test-driven development (or TDD) is a practice where you apprach software development in the following way:

  1. You write a test. This test fails immediately, as you haven't even written any code yet.
  2. You write the smallest piece of code that passes your test and add nothing else.
  3. You refactor the code and improve design while keeping all your tests working.

Then you add another test (which, again, fails by default), you write code that passes the test, you refactor the code so all your tests keep working, et cetera.

This way, tests actually “drive” your development – test first, code later!

But why do it this way? Because when you frontload writing tests, you tend to write rigorous detailed tests that cover almost all edge cases you can think of! You also get an intuition how your code will actually be used, rather than just implemented. And most of all, all your code will be thoroughly tested (as long as you follow the italic part in step 2 ;).

Let's compare it to the traditional way – code first, test later.

Well, what's the issue with that? Commonly what happens is you write a lot of code that does a lot of things – because programming is fun! But then comes writing tests… writing tests for code that's already there is supremely boring. You'll have developed a lot of code that's used nowhere – yet now you have to write tests for it. Even when you find an edge case where your code doesn't work, you'll tend to sweep it under the rug just to keep the existing tests working. All this results in sloppy testing, and most of all – sloppy software!

How do I use it?

TEST_CASE() {
    REQUIRE(vec.add);
}

A common mistake is “over-mocking”. That's when you start testing every little detail – including the implementation of the class itself. Don't do that! You're only supposed to verify the basic functionality, not every single minutia.

Think of it this way – a test should be like a field sobriety test; not an interrogation room. You're supposed to check if a class is “drunk” (or written by someone who was drunk ;) not interrogate it for murder. Walk in a straight line? Not slurring words? Blew zero on breathalyzer? Okay – you're free to go. Don't needlessly extend the search! The debugger – that's the interrogation room.

When do I use it?

When do I avoid it?

Criticism

test-driven-development.txt · Last modified: (external edit)