Simulating dependencies with mocks using Mockito
With unit testing, as opposed to integration testing, we aim to test each class independently. However, many classes have dependencies that we don't want to rely on. So we use mocks.
Mocks are smart objects whose output can vary depending on the input. Mockito is the most popular mocking framework with a concise, yet easy to grasp, syntax.
Getting ready
We'll mock the StringUtil
class with its concat()
method concatenating two String
objects:
public class StringUtil { public String concat(String a, String b) { return a + b; } }
Note
Note that there's no good reason to mock this class, as it's just a convenient example, to show you how to use Mockito.
How to do it…
Follow these steps for simulating dependencies with mocks using Mockito:
Add the
mockito-core
Maven dependency inpom.xml
:<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.10.8</version> ...