Thinking Differently Through Unit Tests

We don’t practice strict TDD where I work, but we make sure that we have a decent code coverage and good unit tests.

Rather than doing TDD by the book all the time I sometimes find myself with a small project wondering how to start and then coming up with the first set of tests that I know will definitely need to pass and then continute from there.

Usually, this „test first, then code“ principle only holds for so long before it breaks down and I find myself switching between writing code and unit tests in no particular order. Nevertheless, it is a good way to start and I usually cover a good deal of code before I’m straying from the pure TDD path to something less structured.

What I noticed when writing tests first is that I focus on completely different things than when I write code the before writing tests. Mostly, when writing tests first I first come up with everything that might go wrong rather than what goes right. Usually, tests for exceptions come first, then all the other conditions where things might not work as expected and last the happy path for when everything goes right.

When writing code first, it’s the other way round: First figure out how to do it, then cover the exceptions. This is probably different for other developers, but in my case it’s a very interesting observation I was able to make about myself and the way I think.

Another good place to practice TDD in small doses is bugfixing. Just write the test first, make sure it fails and then write the code to make it green. When working with untested code, it is a good way to start bringing code coverage up without having to dig through tons of code. It might not be perfect, but it’s a start