Validating if the mocked function was called
Mockito provides “Verify()” which can be used to validate if mock object’s function was called with proper arguments.
verify() can be used to verify that a mocked object
# has been called;
# and with the correct request data;
# and for a certain number of times;
# and with multiple requests in the correct order;
# or has never been called.
following code snippet demonstrates usage of Verify()
import static org.mockito.Mockito.*;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
// @Mock
// MyDatabase databaseMock;
@Test
public void testQuery() {
// Step 1: Instantiate a Mock Object
MyDatabase databaseMock = mock(MyDatabase.class);
// Step 2: Identify and test the conditions to validate feature under
// development
when(databaseMock.fetchResults("condition1")).thenReturn("FName");
verify(databaseMock, times(0)).fetchResults("argument1");
String result1 = databaseMock.fetchResults("condition1");
// Step 3: Validate / Assert the results
Assert.assertTrue("Failed to validate condition1", "FName".toLowerCase().equalsIgnoreCase(result1));
}
}
0 comments