Mockito spy() – mocking and using an object at same time..

If your test method is designed to mock a service under implementation and at same time there is another method which need to use an object of same class, Mockito framework provides spy

for example in previous example where we were mocking MyDatabase class, we can use MyDatabase objects in same test by following code snippet.

package ObjectInstantiation;

import static org.mockito.Mockito.when;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

public class temp implements MyDatabase {

MyDatabase databaseMock;

public void testQuery() {

// Instantiate a real Object
MyDatabase databaseMock1 = new temp();
String result = databaseMock1.fetchResults(“Test “);

// Mock same class

String result1 = databaseMock.fetchResults(“condition1”);

// Step 3: Validate / Assert the results
Assert.assertTrue(“Failed to validate condition1”, “FName”.toLowerCase().equalsIgnoreCase(result1));
Assert.assertTrue(“Failed to validate actual object”, “Test My SQL Query”.toLowerCase().equalsIgnoreCase(result));

public String fetchResults(String Query) {
Query = Query+”My SQL Query”;
return Query;