Unit testing and mocks

I’m one of the converted when it comes to test-driven development. One of the main “aha” moments for me is not to write unit tests - it’s writing testable code. Any code that’s testable is sure to be of a higher quality and easier to maintain than typical spaghetti code.

That brings me to the second part of the title - mocks. The art of mocking objects have taken off over the last couple of years. I feel that there is a danger of abusing them to test code, when the code is not written in a testable way. I’ve seen examples where developers use mocking so much that what you’re testing is the mock object’s functionality - and not your code. In cases like these you’d be much better off refactoring than mocking dependencies.

So here’s my recommendation: focus on writing testable code, and try to reduce the use of mocks. Use it when you have no other method available to test your code.

Photo by Leio McLaren on Unsplash