Automating Test Doubles with Mockito
Explore automating test doubles with Mockito to streamline unit testing in Java. This lesson guides you through integrating Mockito with JUnit 5, creating mocks and stubs, and using TDD to write well-structured tests that reduce repetitive code and improve test reliability.
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:
Writing a stub with Mockito
Let’s see how ...