Mockito mock() Method Example

1. Introduction

In Mockito, the mock() method is a core function that allows us to create mock objects. A mock object simulates the behavior of the real object, allowing developers to test the functionality of the system under test without dealing with external factors like database calls. This article delves into the mock() method, demonstrating its power and simplicity.

2. Example Steps

1. Define an interface with a method signature.

2. Create a test class for the interface.

3. Use the Mockito mock() method to create a mock of the interface.

4. Define the behavior of the mocked interface using Mockito’s when() and thenReturn() methods.

5. Write a test method that uses the mock and asserts the expected behavior.

6. Execute the test.

3. Mockito mock() Method Example

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;

interface PaymentService {
    int getBalance(String userId);
}

public class PaymentServiceTest {

    @Test
    public void testGetBalance() {
        // Step 3: Creating a mock of the PaymentService interface
        PaymentService mockService = mock(PaymentService.class);

        // Step 4: Define behavior for the mock object
        when(mockService.getBalance("user123")).thenReturn(500);

        // Step 5: Utilize the mock and assert
        int balance = mockService.getBalance("user123");
        assertEquals(500, balance);
    }
}

Output:

The test will run successfully, confirming that the mocked behavior for getBalance method of the PaymentService interface operates as expected.

4. Step By Step Explanation

1. We begin with an interface PaymentService that simulates a service that fetches a user's balance.

2. The PaymentServiceTest class is where we will craft our test.

3. Inside the testGetBalance method, we utilize the Mockito mock() method to create a mock instance of the PaymentService interface.

4. With the help of the when() and thenReturn() methods, we stipulate that when getBalance is called with "user123", it should return a balance of 500.

5. After setting up the mock, we proceed to call the getBalance method on our mock instance. We then use the assertEquals function to confirm that the returned value matches our expected result (500).

6. The entire test leverages the mock() method to create a mock instance of an interface and further demonstrates how this can be used to simulate specific behaviors, allowing for effective and isolated unit testing.


Comments