We’ve played around with different testing concepts like mocks and stubs in class, however since we didn’t dive too far into it, I decided I’d look a little bit deeper into the subject of mocking. I found this great overview of it on Michael Minella‘s blog.
Before diving into why mocking is helpful, let’s look at the purpose of mocks in the first place and what they even are. In class we had an example where a student object had a transcript object, and in order to get the student’s remaining credits or current GPA, the student would reference the transcript’s methods. Something like this:
If we wanted to test the Student’s getGPA() method, it would involve calling transcript’s getGPA() method. However, we don’t want to test transcript’s method, we want to test Student’s. How do we know Student.getGPA() does the intended thing, which is call transcript.getGPA()? In his blog post, Michael uses the example of a test that uses the ArrayList object in Java. When we write a test that uses an ArrayList, we don’t want to test the functionality of ArrayList — we want to test our implementation of it and trust that ArrayLists function correctly. Mocks are designed to solve this problem.
A mock is a temporary object that is used in place of the real object that would be used during a test. The mock has default values for all of it’s data types, and so whether or not a test passes is not dependent on the state of the other objects or methods inside of it. In the case above, transcript.getGPA() would return a value of 0.0 if a mock transcript object had been set up beforehand. This is helpful because it allows us to remove the potential puzzle of the functionality of the transcript’s methods and solely focus on the what the student’s getGPA() is actually doing.
There are plenty of different mocking libraries to choose from (we used Mockito in class) and they all function in slightly different ways. The subject of mocking is a deep one, and there are seemingly infinite other concepts like stubs, fakes, dummies, and more which can all be used to ensure that your tests test are as thorough and reliable as possible.
From the blog CS@Worcester – James Blash by jwblash and used with permission of the author. All other rights reserved by the author.