Mocking is a technique used in software testing where you create a simulated version (a mock) of an object or component to mimic its behavior. This aids in test isolation, faster tests and allows tests to focus in on the targeted part of the system.
In my limited experience with mocking, I have not yet used it to reference anything external to the program I was building. My initial thoughts on it were that mocking seemed like it would be a viable tool to use to circumvent some of the complexity of dealing with external references. After reading the blog post, it became clear exactly why that was wrong.
In the simplest terms “Don’t mock what you don’t own” means what it sounds like: when you are writing tests, don’t mock anything that you don’t have complete ownership of. This applies to third party libraries and external systems.
Why, you may ask?
- You don’t own the code, so there is no guarantee about how it will behave in the future. Therefore, mocking it leads to test fragility.
- Code clarity. When you mock external references it forces you to handle the behavior of it, when your focus should be on the behavior of the application you are working on.
- Tight coupling. The tests become tightly bound to external code and the system becomes harder to maintain over time.
What should you do instead? Create a wrapper around the third-party code, then mock the wrapper
I found the proposed solution of wrapping the external “thing” and then mocking the wrapper to be a rather elegant solution. This avoids a lot of the coding gymnastics that would be necessary to maintain the “external” mocks. The author of the blog post made a good point, mocking external object creates faster tests, but fast isn’t enough to justify test fragility and poor tests. This sparked the line of thinking “What is the goal of this tool (mocking) and how does using it in this way align with that?” This was a new thought process for me. Up until this point in my education, most things I have learned took the form of “Here’s a new thing you can do, now do it”. This new thought process adds to that the important layer of discernment over my toolbox of skills. Afterall, you can (in theory) hammer a nail with a screwdriver if you hit it enough times, but you will get some funny looks, and your life would be much easier if you had just chosen a hammer. In my work, I will be certain to keep this in the forefront of my mind.
TLDR: Only mock code that you own and choose your tool wisely.
This blog post was written in response to : https://8thlight.com/insights/thats-not-yours
From the blog CS@Worcester – CurrentlyCompiling by currentlycompiling and used with permission of the author. All other rights reserved by the author.