Andrez Segovia

Validate the arguments passed to a method

Published on • • 95 Words

The Mockito framework has the ArgumentCaptor class that can be use to validate the arguments passed to a mocked method.

 1import org.junit.jupiter.api.Test;
 2import org.mockito.ArgumentCaptor;
 3
 4import static org.junit.jupiter.api.Assertions.assertEquals;
 5import static org.mockito.Mockito.*;
 6
 7public class MyServiceTest {
 8
 9    @Test
10    public void testMethodArgument() {
11        // Arrange
12        MyDependency mockDependency = mock(MyDependency.class);
13        MyService myService = new MyService(mockDependency);
14
15        // Act
16        myService.execute("testArgument");
17
18        // Capture the argument
19        ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
20        verify(mockDependency).methodToBeCalled(argumentCaptor.capture());
21
22        // Validate the captured argument
23        String capturedArgument = argumentCaptor.getValue();
24        assertEquals("testArgument", capturedArgument);
25    }
26}