Mockito BDDMockito willCallRealMethod() Method Example

1. Introduction

Mockito, in its essence, provides a mechanism to override the behavior of methods in mocked objects. But there might be scenarios where, instead of mocking a method's behavior, we'd like to call the real underlying method of the mocked object. This is where willCallRealMethod() from BDDMockito comes into play. In this example, we'll explore how to use BDDMockito's willCallRealMethod() to instruct Mockito to execute the actual implementation of a method, rather than a mocked version.

2. Example Steps

1. Create a simple class with a method that has a real implementation.

2. Set up a JUnit test class.

3. Mock the class and use BDDMockito's willCallRealMethod() to instruct the mock to call the real method implementation.

4. Run the test and verify the output matches the real method's behavior.

3. Mockito BDDMockito willCallRealMethod() Method Example

// Step 1: Create a simple class
class SimpleService {
    String fetchMessage() {
        return "Real Message from SimpleService";
    }
}

// Step 2: Set up a JUnit test class
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.*;
import static org.junit.jupiter.api.Assertions.*;

public class SimpleServiceTest {

    @Test
    public void testFetchMessage() {
        // Mock the SimpleService class
        SimpleService mockService = mock(SimpleService.class);

        // Step 3: Use BDDMockito's willCallRealMethod()
        willCallRealMethod().given(mockService).fetchMessage();

        // Invoke the method and check the result
        String result = mockService.fetchMessage();
        assertEquals("Real Message from SimpleService", result);
    }
}

Output:

Test passed successfully. The returned message is "Real Message from SimpleService".

4. Step By Step Explanation

1. We started with a SimpleService class that has a method named fetchMessage(), which returns a simple message.

2. In the SimpleServiceTest class, we created a mock of the SimpleService.

3. Using BDDMockito's willCallRealMethod(), we instructed Mockito to call the real fetchMessage() method when it's invoked on the mock object.

4. Finally, we ran the test which invoked the fetchMessage() method on the mock. Since we used willCallRealMethod(), the output was the real message from the SimpleService class and not a default or mocked one. We then verified this with an assertEquals() to ensure the test's integrity.


Comments