Practical guide for Mockito

By Bhushan Nikhar

Here's practical Mockito guide.
I am writing this guide for someone who already knows JUnit 5 and wants to quickly learn Mockito to start writing testcases.

What's Mock and why use Mockito?

It's uncommon for a single class to contain all the logic in isolation, which is why we rarely write unit tests for individual, standalone classes. In most cases, classes with logic are interdependent, meaning that to test one class, you may need to initialize its dependencies. However, including these dependencies in unit tests can introduce unnecessary complexity, making the tests harder to maintain and interpret. They can also pollute the test results, making it more difficult to isolate and verify the behavior of the class being tested.

To avoid these issues, we use mocks for the dependencies. Mocks are simplified, dummy versions of dependencies that return pre-defined values, allowing us to isolate the behavior of the class under test without the overhead of dealing with real dependencies.

There's only one Golden rule while mocking
"You can not mock instance of class being tested."


You can however make your mock respond to your inputs based on specific scenarios. That is what Mockito framework is used for.

GreetingService

Loading...
GreetingService
Class Under Test
Loading...
In Test Method
Mock

Return default values

We have CurrencyConverterService that converts currency in USD to INR based on external dependency of currency exchange.

When testing convertUsdToInr method, we will need to mock the external currency exchange to ensure that our code functions correctly.

CurrencyConverterService

Loading...
CurrencyConverterService
Class Under Test

CurrencyConverterServiceTest

Loading...
testConvertUsdToInr
Passed