Writing Tests First

The test-driven development (TDD) methodology advocates the following practice (in that order):

  1. Write tests for the feature you want to implement.
  2. Watch the tests fail.
  3. Write enough code for the tests to pass.
  4. Refactor your code.

I usually don’t care about the order in which the tests and the production code are written. I am used to a more traditional approach — write the code, and then the tests. Recently I realized one big benefit of writing tests first (in addition to all the other benefits the TDD advocates have been saying). Writing the tests first and watching them fail make sure the tests are indeed working, and after you write more code to make the tests pass, you are sure that the new code is indeed doing the work. If you write the production code first and then write the tests, the tests pass, but then you cannot be sure whether your code is indeed correct or your tests are broken (pass when they shouldn’t have).

In a few places in one of my personal projects, I mistakenly used assert() instead of the assertTrue() JUnit function. assert() is only effective in debug mode, so these tests end up useless.

Post a Comment

Your email is never published nor shared.