Lifecycle of a Mockito test
Lifecycle of Mock objects
Mockito allows execution of tests for classes with dependency under development (or external databases whose access is not available at run-time).
Creating and accessing mock objects generally follow three steps
1. Instantiate mock object for external dependency (or feature under development)
2. Develop tests for above mock object
3. Assert the results.
Mockito framework can be used in conjunction with TestNG and allows to instantiate mocks by following techniques:
1. Instantiation via code
2. Use Mockito framework annotations (@Mock, @InjectMocks, @RunWith(MockitoJunitRunner.class), @Captor etc)
In this example, I am going to mock the Database response (for a feature under development) and identify how a automation can be performed in parallel to DB features are implemented.
Let’s take an example the new feature under test for a database can be tested with multiple SQL Queries which fetch details to test feature under development.
import static org.mockito.Mockito.*;
import org.junit.Assert;
import org.junit.Test;
public class MockitoTest {
@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");
String result1 = databaseMock.fetchResults("condition1");
// Step 3: Validate / Assert the results
Assert.assertTrue("Failed to validate condition1", "FName".toLowerCase().equalsIgnoreCase(result1));
}
}
In above code MyDatabase is object of database class under development.
Above mock can be instantiated with Mockito framework as follow:
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");
String result1 = databaseMock.fetchResults("condition1");
// Step 3: Validate / Assert the results
Assert.assertTrue("Failed to validate condition1", "FName".toLowerCase().equalsIgnoreCase(result1));
}
}
0 comments