

In contrast to creating a mock, creating a spy requires an instance to spy on. What Is a Spy?Ī spy is the other type of test double that Mockito creates. After the test, you can query the mock to see what specific methods were called or check the side effects in the form of a changed state.īy default, Mockito provides an implementation for every method of the mock. With Mockito, you create a mock, tell Mockito what to do when specific methods are called on it, and then use the mock instance in your test instead of the real thing. In short, mocks are used as a replacement for a dependency. What Is a Mock?Ī mock in unit testing is a created object that implements the behavior of a real subsystem in controlled ways. We’ll be focusing only on two types of test doubles, “mocks” and “spies,” as these are heavily employed by Mockito. A stub is a kind of test double other kinds of doubles include fakes, mocks, spies, dummies, etc. Such implementations usually have hard-coded logic.

A traditional, well-known approach here is to create “stubs”-specific implementations of an interface suitable for a given scenario. Furthermore, we’ll use slightly different implementations of these dependencies when testing different behaviors. Since we’re testing the smallest “unit” of code, we don’t need to use actual implementations of these dependencies. Unit tests are designed to test the behavior of specific classes or methods without relying on the behavior of their dependencies. We’ll be using JUnit as a unit testing framework, but since Mockito is not bound to JUnit, you can follow along even if you’re using a different framework. We’ll also explore Mockito’s internals to better understand its design and caveats. In this article, we’ll cover creating and configuring mocks and using them to verify the expected behavior of the system being tested.

One such tool is Mockito, an open-source framework that lets you create and configure mocked objects for tests. Unit testing has become mandatory in the age of Agile, and there are many tools available to help with automated testing. It has been modified to include recent sources and to align with our current editorial standards. Editor’s note: This article was updated by our editorial team on January 6, 2023.
