DEV Community


Discussion on: When do you write your tests?

craser profile image
Chris Raser • Edited

Yep! I'm sure you've heard the old joke: "In theory, theory and practice are the same. In practice, they're not."

I find that lots of people disagree strongly about how/when/why tests "should" be written, but mostly agree on how to handle specific situations.

If I'm debugging, then the first thing I do is write a test to detect the bug.

If I'm building new functionality, I generally alternate between writing tests and writing application code, like so:

  • Write some super-simple implementation of what I need.
  • Write a few tests to make sure I have the basic functionality right.
  • Fix any bugs I find.
  • Write tests for edge cases, error conditions, etc.
  • Use those tests as a checklist for the rest of the work to be done.

So you can see that for the initial "happy path" functionality, I often write the code first, then the test. And then for edge cases and error conditions, I write the tests first.

And I often write test cases after doing new development to help support refactoring and maintenance efforts.

Sarah Mei's article on Five Factor Testing is excellent. She talks about fitting your testing practices to your team goals.