I’m in love with a mocking framework
I was recently introduced to Mockito by our new Java developers. Mocking frameworks are used to isolate unit tests to only exercise the code under test. Anything outside is replaced with a mock object that returns an expected result where needed. It’s a simple form of test isolation that’s more productive than stubbing out code. Any testing that needs to cross a boundary are software integration tests (quite distinct from real world integration tests that engineers know and love).
Mocking frameworks have been in common use for many years. I had tended to avoid the practice except when interfacing with some of Java’s old and difficult to test against classes (like HttpServletRequest). I used EasyMock but found it tedious because of the boilerplate code in each test to set up the mocks and expectations. Coding shouldn’t be painful or tedious. If it is, good developers will avoid the task to do something more interesting.
Mockito seems to directly address some of the tedium of EasyMock:
- Plain mock objects can be set up via annotation to reduce the setup boilerplate. The framework can also inject them into the class under test.
- Expectations only need to be written for the explicit interactions of interest. We seem to write far fewer expectations now (only exactly what is needed)
- The expectations and verification APIs are similar to EasyMock but again reduce the amount of code needed for the same outcome
- Using Powermock as well it’s easy to test against legacy code. Powermock uses bytecode manipulation to mock static methods and constructors (among other edge case).
I’m always fascinated when people take something that’s assumed best practice and suddenly makes exceptional improvements. The tools and practices in Java keep getting better while the language itself has remained relatively stagnant.