The previous lessons have shown examples of using stubs and mocks to test code. We have been writing these test doubles by hand. It’s obviously quite repetitive and time-consuming to do this. It raises a question: can this repetitive boilerplate code be automated away? Thankfully for us, it can be. This lesson will review the help available in the popular Mockito library. Mockito is a free-of-charge open-source library under the MIT license. This license means we can use this for commercial development work, subject to agreement by those we work for. Mockito provides a large range of features aimed at creating test doubles with very little code.

Getting started with Mockito

Getting started with Mockito is straightforward. We pull in the Mockito library and an extension library in our Gradle file. The extension library allows Mockito to integrate closely with JUnit 5. The excerpt of build.gradle looks like this:

Get hands-on with 1200+ tech skills courses.