When switching to Kotlin, static methods are moved into a companion object. However, there is no obvious way to unit test other methods which call these "static method".
In Java, we could use PowerMockito's MockStatic(SomeClass.class) to verify a static method is called in the method under test. PowerMock loses its magic in Kotlin.
For testing, I have create the following classes.
public class DummyJava {
static public Void staticMechod(){
System.out.print("Dummy method is called");
return null;
}
}
class DummyCompanion {
companion object {
fun someCompanionMethod(){
System.out.printf("companion method is called\n")
}
}
}
Now there is a another class which calls the DummyCompanion.someCompanion
public class DummyWrapper {
public void callAStaticMethod(){
DummyJava.staticMechod();
}
public void callCompanionMethod(){
DummyCompanion.Companion.someCompanionMethod();
}
}
To unit test callAStaticMethod()
We used the following
@RunWith(PowerMockRunner.class)
@PrepareForTest({DummyJava.class, DummyCompanion.Companion.class})
public class staticClassTest {
//This case works
@Test
public void testForStaticMethod() {
PowerMockito.mockStatic(DummyJava.class);
DummyWrapper testObject = new DummyWrapper();
Mockito.when(DummyJava.staticMechod()).thenCallRealMethod();
testObject.callAStaticMethod();
PowerMockito.verifyStatic(Dummy.class);
DummyJava.staticMechod();
}
//This case doesn't work. It always passes.
@Test
public void testForCompanionMethod() {
PowerMockito.mockStatic(DummyCompanion.Companion.class);
DummyWrapper testObject = new DummyWrapper();
testObject.callCompanionMethod();
PowerMockito.verifyStatic(DummyCompanion.Companion.class,Mockito.times(1));
DummyCompanion.Companion.someCompanionMethod();
}
My question is how to verify the companion method is called.