The Way of Testivus says thus on the matter of when to write unit tests:
The best time to test is when the code is fresh
Your code is like clay.
When it’s fresh, it’s soft and malleable.
As it ages, it becomes hard and brittle.
If you write tests when the code is fresh
and easy to change, testing will be easy
and both the code and the tests will be strong.
The key thing to take away form this is that you write code early in the process when you can still think about what the code is doing. When doing this, you think about what is testable and what isn't. Another bit from the Way of Testvius...
Think of code and test as one
When writing the code, think of the test.
When writing the test, think of the code.
When you think of code and test as one,
testing is easy and code is beautiful.
One thing that I like about The Way of Testivus rather than more dogmatic statements is it specifiably calls out dogma and says don't get stuck on it. Writing the test is more important than following rules set in stone.
Write tests.
Write tests early.
A poor written test is better than no test.