Verify that the service method is called once when controller method is invoked
Preconditions (2)
✅ Expected Result: The test passes if the service method is called exactly once during the controller method execution
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.
Now add data-driven testing to verify the service method is called for different controller methods
verify() in JUnit testing with mocks?verify()verify() is used to check interactions with mock objects, specifically if certain methods were called.mock(), asserting return values is done by assertEquals(), and initializing data is unrelated to verify().save() was called exactly once on a mock object repository?verify(mockObject, times(n)).method() to check method call count.MyService service = mock(MyService.class); service.process(); verify(service, times(2)).process();
process() is called once on service.process() to be called twice (times(2)), but it was called once.List<String> list = mock(List.class);
verify(list).add("item");
list.add("item");verify() checks if a method was called before it is invoked.verify() is called before list.add("item"), so no call happened yet to verify.updateStatus(String status) was called exactly once with argument "ACTIVE" on a mock userService. Which code snippet correctly achieves this?times(1) in verify.times(1) but anyString() matches any argument, not specifically "ACTIVE".Pass the test and this pattern moves unknown