class A {
public static int f1() {
return 1;
}
public static int f2() {
return A.f1();
}
}
class ATest {
@Test
void testF2() {
try (MockedStatic<A> aStatic = Mockito.mockStatic(A.class)) {
aStatic.when(A::f1).thenReturn(2);
int ret = A.f2(); // getting 0 here
assertEquals(ret, 2);
} catch(Exception e) {
}
}
}
In the testF2 I want to test static function A::f2().
And it internally calls another static function A::f1().
I did stub A::f1() to return 2 using "MockedStatic" and "when" way.
But it's not working, it's returning 0.
How to solve it?
I think you miss to specify a mock behavior:
by telling the mock what to do when
A.f2()is invoked, test runs fine.Update:
Mocks do what you tell them, if you don't tell what to do when a method is invoked they do nothing, that's why you have to mock
f2too.You want to test
A, then mock it is not your friend. I normally use aMockito.spy()to partially mock my subject under test .You want to mockf1but testf2, I don't thinkspyapplies here because there is no instance to spy..I suggest you to rearrange
Aavoiding static methods if possible or using parameters you can mock.