验证伴随对象方法的单元测试(模拟伴随对象)
2022-09-04 07:10:36
切换到 Kotlin 时,静态方法被移动到伴随对象中。但是,没有明显的方法来单元测试其他调用这些“静态方法”的方法。
在Java中,我们可以使用PowerMockito的MockStatic(SomeClass.class)来验证在被测方法中调用的静态方法。PowerMock 在 Kotlin 中失去了魔力。
为了进行测试,我创建了以下类。
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")
}
}
}
现在有另一个类调用DummyCompanion.someCompanion
public class DummyWrapper {
public void callAStaticMethod(){
DummyJava.staticMechod();
}
public void callCompanionMethod(){
DummyCompanion.Companion.someCompanionMethod();
}
}
为了单元测试,我们使用了以下内容callAStaticMethod()
@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();
}
我的问题是如何验证伴随方法的调用。