how to call real non-static non-void method using mock object

In this post under Mockito, I will show with example how to configure Mockito to call mock object’s real non-static non-void method instead of stubbed one.

For our example, we will use below classes

IndianCash

package package7;
public class IndianCash {
public double getCash() {
return 10;
}
}

IndianCash

package package7;
public class IndiaToUSACashConverter {
private IndianCash indianCash;
public double getUSACash() {
return indianCash.getCash() * 0.011;
}
}

As you can see in the above code, “IndiaToUSACashConverter” is depender which depends upon “IndianCash” the dependee.

We will be testing the methods of “IndiaToUSACashConverter” class. So I have to mock “IndianCash” class object.

Below is the test class

Test class

package package7;
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;
import package6.IndiaToUSACashConverter;
import package6.IndianCash;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class IndiaToUSACashConverterTest {
@InjectMocks
private IndiaToUSACashConverter indiaToUSACashConverter;
@Mock
private IndianCash indianCash;
@Test
public void testGetUSACash() {
//Mocking the method behavior
when(indianCash.getCash()).thenReturn(20.0);
double result = indiaToUSACashConverter.getUSACash();
assertEquals(0.21999999999999997, result);
//Calling the real method
when(indianCash.getCash()).thenCallRealMethod();
result = indiaToUSACashConverter.getUSACash();
assertEquals(0.10999999999999999, result);
}
}

In the above code, at line 25, I stubbed the method “getCash” using Mockito’s “when” and “thenReturn” method to return hardcoded 20.0 value when “indianCash” object’s “getCash” method is called.

But at line 30, I removed the stub created at line 25 by calling Mockito’s “thenCallRealMethod”.

From this point onwards, whenever we call “getUSACash” method of “indiaToUSACashConverter”, it will call “indianCash” mock object’s real method “getCash” instead of stubbed one.

In this way we can configure Mockito to call mock object’s real method instead of stubbed one.

Leave a comment