Issue
My code:
class C:
public class C{
public int methodC(){
return 1000;
}
}
class B:
public class B{
private static C c;
public static int methodB(){
int b = c.methodC();
return b;
}
}
class A:
public class A {
public int methodA(){
int a = B.methodB();
return a;
}
}
class TestA:
class TestA{
@InjectMocks
A a;
@Mock
C c;
public void testMethodA(){
when(c.methodC()).thenReturn(5);
int result = a.methodA();
assertEquals(result, 5);
}
}
Even I mock c.methodC()
, the methodC
call in methodB
returns null
.
How can I mock the methodC
call?
I cannot alter the source code but to do changes only in TestA
class
Also I cannot use PowerMockito
too.
Solution
Here is a way to make it work using your constraints:
A a = new A();
C c = Mockito.mock(C.class);
@Test
public void testMethodA(){
try {
Field c = B.class.getDeclaredField("c");
c.setAccessible(true);
c.set(null, this.c);
} catch (Exception e) {
e.printStackTrace();
}
Mockito.when(c.methodC()).thenReturn(5);
int result = a.methodA();
assertEquals(result, 5);
}
Answered By - jnorman