In this post under Mockito, I will show with example how to stub a non-static non-void method of a mock object to return a hardcoded value.
For our example, we will use the below classes
IndianCash
package package6;public class IndianCash { public double getCash() { return 10; }}
IndiaToUSACashConverter
package package6;public class IndiaToUSACashConverter { private IndianCash indianCash; public double getUSACash() { return indianCash.getCash() * 0.011; }}
As you can see, the class “IndiaToUSACashConverter” depends upon “IndianCash” class.
So “IndiaToUSACashConverter” becomes dependee and “IndianCash” becomes dependent.
We need to test “IndiaToUSACashConverter” class, so we will create a mock of “IndianCash” class and stub its non-static non-void method to return something other than 10.
Below is the test class
IndiaToUSACashConverterTest
package package6;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 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() { when(indianCash.getCash()).thenReturn(20.0); double result = indiaToUSACashConverter.getUSACash(); assertEquals(0.21999999999999997, result); }}
At line 15, we declare field “indiaToUSACashConverter” of type “IndiaToUSACashConverter” and annotate it with “@InjectMocks” annotation.
At line 18, we declare field “indianCash” of type “IndianCash” and annotate it with “@Mock” annotation.
So Mockito framework will inject mock of “indianCash” inside “indiaToUSACashConverter” object.
Now in the test method “testGetUSACash”, at line 22, we are telling Mockito framework that when “indianCash” object’s “getCash” method is called then return “20.0” value. For this purpose we are using Mockito’s “when” and “thenReturn” methods.
In this way, we create a stub of a non-static non-void method of a mock object to return a hardcoded value.