0
0
JUnittesting~15 mins

verify() for interaction verification in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify that the service method is called once when controller method is invoked
Preconditions (2)
Step 1: Create a mock of the service class
Step 2: Inject the mock service into the controller
Step 3: Call the controller method that should invoke the service method
Step 4: Verify that the service method was called exactly once
✅ Expected Result: The test passes if the service method is called exactly once during the controller method execution
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Verify interaction with mock service method using Mockito.verify()
Best Practices:
Use @ExtendWith(MockitoExtension.class) for Mockito support
Use @Mock annotation for mocks
Use @InjectMocks to inject mocks into the class under test
Verify interactions explicitly with Mockito.verify()
Avoid unnecessary stubbing
Automated Solution
JUnit
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class ControllerTest {

    @Mock
    private Service service;

    @InjectMocks
    private Controller controller;

    @Test
    void testServiceMethodCalledOnce() {
        // When
        controller.callServiceMethod();

        // Then
        verify(service, times(1)).performAction();
    }
}

// Supporting classes for context
class Controller {
    private final Service service;

    public Controller(Service service) {
        this.service = service;
    }

    public void callServiceMethod() {
        service.performAction();
    }
}

interface Service {
    void performAction();
}

This test uses JUnit 5 and Mockito to verify interaction between Controller and Service.

@ExtendWith(MockitoExtension.class) enables Mockito support.

@Mock creates a mock Service instance.

@InjectMocks injects the mock into Controller.

The test calls controller.callServiceMethod(), which should call service.performAction().

Mockito's verify(service, times(1)) checks that performAction() was called exactly once.

This ensures the controller interacts correctly with the service.

Common Mistakes - 4 Pitfalls
{'mistake': 'Not using @ExtendWith(MockitoExtension.class) and missing mock initialization', 'why_bad': "Mocks won't be initialized, causing NullPointerException", 'correct_approach': 'Use @ExtendWith(MockitoExtension.class) to enable Mockito annotations'}
Verifying method call without specifying times()
Verifying a method that was never called
Using verify() before the method call
Bonus Challenge

Now add data-driven testing to verify the service method is called for different controller methods

Show Hint