TDD in existing projects

You most probably already have projects that have been implemented without any tests. It is much harder to add tests to an existing project than it is to write them first. When you don't keep in mind that you need to write a test for code sometime in the future, the code itself will become hard to test. It is often easier to tie the different parts of the app together instead of keeping them separated with a clear and defined interface to each other. As a result, it becomes hard to separate micro features in order to test them with unit tests. In addition to this, testing methods with many side effects can be cumbersome to deal with.

When writing the tests initially, you will automatically think about the tests. The code naturally becomes easier to test and more modular.

Back to your existing projects. What could you do to add tests? The way to go is to start small. Don't rewrite all the methods using TDD. This won't work, and you will most probably remove all the tests when you realize how hard this is.

Instead, when you find a bug in the code, try to write a failing test for the bug, and make the test pass. This way, you can improve your code, and make sure that this bug never returns without being noticed. Unfortunately, this method will not work all the time, as your code might have a lot of coupling. But you should try it anyway. Take some time to think about what you would have to change to make this feature testable.

A second approach is to add features using TDD. You may have many ideas about how you could improve your app. Let's say, in the example of the ToDo app, you would like to add the ability to share the number of ToDo items on Twitter to show all your friends and followers how busy you are. Even if the app doesn't have any tests, we could break this feature into several micro features and write tests for them before we implement the code.

The most important thing is to start writing tests. The tests don't have to be perfect. In the beginning, a nonperfect test is better than no test. Later, you may realize that some of the tests could be improved and even deleted. That is not a problem. Just keep adding tests. The more tests you write, the better your tests will become.