Are you Mocking me?

The idea of mock objects used for testing makes me very excited. After struggling through an assignment on mocking in the very class I am writing this blog for, my excitement started to waver. Luckily I was able to get everything working after messing with gradle dependencies and the locations of files within the project and it was really a joy to see just how powerful mocking could be. I decided to look at mocking in greater detail for this blog post, because while the assignment we did in class did set up a good introduction, I feel like most of the assignment was spent setting up mockito, a really handy java mocking framework.

I found a really thorough article about mock testing written by Michael Minella (over a decade ago!) over at Dzone.com. While this article is ancient in terms of how quickly technology changes, I feel like all of the information given is still very relevant today, even if frameworks have changed a bit since then.

In the real world it is almost impossible to program without having to use dependencies. Mocking is one way to make sure that tests are only testing what needs to be tested, rather than testing the method in question and all of its dependencies. It allows you to create “Mock” objects that return desired outputs for their methods since tests should assume that any other methods that need to be called are working as intended. To reiterate what was said in the article, If a method has a dependency that returns an ArrayList, you most likely aren’t testing that ArrayList works as intended. You should assume that it works and test the method under that assumption. Mocks are proxy objects that only return what is necessary, eliminating any potential issues where the dependency could have an issue that would muddle the usefulness of the tests.

The article doesn’t go into detail about any specific frameworks but does talk about the how exactly the different types of frameworks work. According to the article, Mocking frameworks that use proxy objects, objects that are injected into the test file without modifying any other code, are far more popular than any other types of mocking frameworks.

This article is a must read for anyone looking to start using mocking in their unit tests. I feel like dealing with dependencies in my unit tests is something that I find myself struggling with and Mocking is most certainly a good solution to that.

Leave a comment