Failure First

Test-driven development (TDD) is a software development process that uses an initially failing automated test case to define a desired improvement or new function. After the failed test, a minimum amount of code is written to pass that test, and one refactors the new code to acceptable standards.

Learning TDD can be difficult and strange at first. If you forget to write a test first, your reaction is to stop what you’re doing and write it. But the test won’t fail in a useful way since the function isn’t finished. Even writing the test beforehand can be a challenge because it can change too much and slow you down. , Building a new habit takes time and practice, so even though writing the test first may seem strange, it’s important to keep trying.

While you already know the test is going to fail, it’s important that the test fails in the expected way. For example, when you first write the test, you expect a failure because the function being tested doesn’t exist yet. However, if the test fails because a library isn’t included or the compiler throws an error, then there’s an issue with the environment. It can’t be a bug with your code because you haven’t written any yet.

When you’re learning TDD, you may forget to write a test beforehand. Instead of dropping everything to write a test, get to a point where a test could fail in an expected way and then write it. What does “an expected way” mean? A basic test will create an object, call the function under test, and then verify the results. An expected failure is one of two things: either the object or function doesn’t exist, or the result is not what it should be. When you realize you’ve written code without a matching test, work to get the code to a place where test will fail in one of those two ways, then write the failing test.

If you’re having trouble remembering to test first, ask for help. You don’t necessarily have to pair with a experienced TDD developer, just someone (or something) to remind you to write the tests. Pairing with another programmer who is also learning TDD is great because you can alternate writing and fixing the tests. If you don’t have a partner, set up some sort of reminder to keep you on track.

When learning a new habit, the most important tip is to focus on practice over perfection. Don’t worry about getting mocking or dependency injection setup or a serious testing framework; build the habit of writing tests first. Don’t be afraid to throw away the tests when they age poorly - by that point, you will have built the habit and will have learned what makes a good test so you can write better ones.