For the final blog entry for this class, I decided to cover a topic that I’ve had personal experience with but wanted to review for further review and understanding, mocking and specifically, mockito. I found an article on toptal.com by Ivan Pavlov about mockito that is a guide for everyday use of the tool, exactly what I was looking for! The article has sections that includes some in depth analysis that could likely be used as a more in depth documentation for several aspects of mockito. The article also includes some insight into what mocks and spies are in the context of testing, unit testing specifically as well as some examples of the mockito tool in action.
For unit tests, we are testing the smallest unit of code possible for validity. The article states that the dependencies are not actually needed because we can create empty implementations of an interface for specific scenarios known as stubs. A stub is another kind of test double, along with mocks and spies, which are the two test doubles relevant to mockito. According to the article “mocking for unit testing is when you create an object that implements the behavior of areal subsystem in controlled ways.” They basically serve as a replacement for a dependency in a unit test. Mockito is used to create mocks, where you can tell mockito what you want to do when a method is called on a mocked object.
A spy for unit testing is another test double used by mockito. A spy, unlike a mock, requires a non-mocked instance to “spy on”. The spy “delegates all method calls to the real object and records what method was called and with what parameters”. It works as you would expect a spy to, it spies on the instance. In general, mocks are more useful than the spy as they require no real implementation of the dependency as the spy does. The spy is also an indicator that a class is doing too much, “thus violating the single responsibility principle” of clean code.
Mocking with mockito can be used in a situation where you want to test that an object is being assigned a specific value when a method is called on it and certain parameters are met. A mock does not require the implementation of the methods to be written yet as you can assign values when a method is called by the power of mockito. This is why mockito is such a popular testing tool and mocking is such a popular testing strategy, and why I’ll continue to utilize it whenever relevant.
Link to original article: https://www.toptal.com/java/a-guide-to-everyday-mockito
From the blog CS@Worcester – The Road to Software Engineering by Stephen Burke and used with permission of the author. All other rights reserved by the author.