Unit testing and mocks

Unit testing and mocks

I’m one of the converted in terms of 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. However, I feel that there is a real danger of abusing them in order to test code, when the code is not written in a testable way. I’ve seen many examples where mocking is used in such abundance 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 minimize the use of mocks. Only use it when you have no other method available to test your code.

Photo by Leio McLaren on Unsplash


See also