Ideally, you should be following TDD principles, if you’re not familar with them then I recommend watching the following video from Uncle Bob.
TDD can provide instant feedback on whether or not the code you’re writing is doing the correct thing, which can be very useful particularly in complex applications that are hard to test otherwise. Sometimes though it’s not possible to follow TDD principles, for example you may find yourself adding tests to an existing code base, in this situation, what is the best approach?
Use a mocking library
A mocking library is very helpful, when writing unit tests you should try to focus on the scope of the code that you are testing, that way your tests aren’t coupled to the code and changes to other functions won’t affect your test.
Understand what the code is doing
Where possible try to focus on what the outputs of the code are and not on how it gets them but..
Don’t be afraid to just assert that something is called
Sometimes your code won’t have a return value or an exception that you can validate, some code exists purely to call other functions. For example:
Is it worth testing mutliple_calls? I would argue yes, it’s purpose is to call a series of functions in a specific order, so let’s make sure it does just that with a test. When faced with code like this just ask yourself, “Am I getting value by adding a test here or am I just coupling the tests to the code?”
Clean as you go
If you’ve written tests that properly cover a piece of code, then why not clean that code a little? You’ve got the tests now, so if you break anything they will tell you!
So this is the last post in my series on unit testing. Hopefully it has been useful, I’ve definitely enjoyed writing it!