I have got 4 classes lets says A, B, C, D each calling on methods from another one.
now I have mocked class A, and want to mock a method using mockito
A
Try by creating mock of each of the nested object and then mock the individual method called by each of these object.
If the target code is like:
public Class MyTargetClass {
public String getMyState(MyClass abc){
return abc.getCountry().getState();
}
}
Then to test this line we can create mocks of each of the individual nested objects like below:
public Class MyTestCase{
@Mock
private MyTargetClass myTargetClassMock;
@Mock
private MyClass myclassMockObj;
@Mock
private Country countryMockObj;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void test01(){
when(myclassMockObj.getCountry()).thenReturn(countryMockObj);
when(countryMockObj.getState()).thenReturn("MY_TEST_STATE");
Assert.assertEquals("MY_TEST_STATE", myTargetClassMock.getMyState(myclassMockObj));
}
}