Practical Guide for Mockito

By Bhushan Nikhar | Simple Technology

Mockito Testing Illustration

Here's a practical guide for Mockito. This guide is written for developers who already know JUnit 5 and want to quickly learn Mockito to start writing efficient and isolated test cases.

Mockito Concepts

Mockito is a powerful mocking framework for Java that allows developers to create mock objects to simulate real dependencies. By mocking dependencies, you can focus on testing the behavior of the class under test — not the behavior of its dependencies.

What’s a Mock and Why Use Mockito?

It’s uncommon for a single class to contain all logic in isolation. In most real-world cases, classes depend on other services or components. Directly using these dependencies during unit testing can introduce unnecessary complexity, make tests brittle, and slow them down.

To solve this, we use mocks — dummy versions of dependencies that return pre-defined values. This ensures your tests remain isolated, fast, and focused.

Golden Rule: You cannot mock the class being tested itself. Only mock its dependencies.

Mockito allows you to make these mocks respond to your inputs based on specific scenarios. Let’s explore an example.

Example: GreetingService

Class Under Test

// Main class: GreetingService
public class GreetingService {
    private final HelloService helloService;

    public GreetingService(HelloService helloService) {
        this.helloService = helloService;
    }

    public String greet() {
        // Joins Hello from HelloService with "World"
        return helloService.sayHello() + " World";
    }
}

In Test Method

// Create a mock of the HelloService class
HelloService mockHelloService = mock(HelloService.class);

//Given
when(mockHelloService.sayHello()).thenReturn("Hello");

//When
GreetingService greetingService = new GreetingService(mockHelloService);
String result = greetingService.greet();

//Then
assertEquals("Hello World", result);

✅ greet_should_return_HelloWorld_when_mocked — Passed

Return Default Values

By default, Mockito returns sensible default values for mocks. For example:

  • 0 for numeric types (int, double)
  • false for booleans
  • null for objects

Let’s see how this helps when testing a class that depends on an external service.

Example: CurrencyConverterService

Class Under Test

public class CurrencyConverterService {

    // Method that gets the current exchange rate for USD to INR (in reality, this could be an API call)
    public double getExchangeRate() {
        // In a real scenario, this would connect to an API and return the exchange rate.
        throw new UnsupportedOperationException("Real API call not implemented.");
    }

    // Method that converts a given amount in USD to INR using the exchange rate
    public double convertUsdToInr(double usdAmount) {
        double rate = getExchangeRate();
        return usdAmount * rate;
    }
}

In Test Method

@Test
public void testConvertUsdToInr() {
    //Given
    // Create a mock of the CurrencyConverterService class
    CurrencyConverterService converterServiceMock = mock(CurrencyConverterService.class);

    // Stub the getExchangeRate method to return a fixed exchange rate (e.g., 75.50 INR for 1 USD)
    when(converterServiceMock.getExchangeRate()).thenReturn(75.50);

    //When
    // Call the convertUsdToInr method with a test amount (100 USD)
    double usdAmount = 100.0;
    double expectedInr = 7550.0;

    //Then
    double actualInr = usdAmount * converterServiceMock.getExchangeRate();
    assertEquals(expectedInr, actualInr);
}

✅ testConvertUsdToInr — Passed

Conclusion

Mockito is an essential tool for writing effective unit tests in Java. It allows you to isolate components, simulate dependencies, and ensure your tests focus solely on the class under test.

Combined with JUnit 5, Mockito provides a powerful and flexible testing setup that encourages cleaner, faster, and more reliable code.

Author: Bhushan Nikhar | Blog: Simple Technology | Category: Java Testing, Mockito, Best Practices