gpt4 book ai didi

java - 调用验证伴随对象方法的单元测试(模拟伴随对象)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:00 26 4
gpt4 key购买 nike

当切换到 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();
}

我的问题是如何验证配套方法是否被调用。

最佳答案

方案一:在调用类中添加调用函数

public class DummyWrapper {
val foo get() = DummyCompanion.Companion

public void callAStaticMethod(){
foo.staticMechod();
}

public void callCompanionMethod(){
foo.someCompanionMethod();
}
}

在测试类中,我们可以使用 Mockito 为 get() 函数提供 stub 并验证它是否被调用。

@Test
fun testCase{
....
val mockCompanionObj: DummyCompanion.Companion = mock()
val wrapper = DummyWrapper()

whenever(wrapper.foo).thenReturn(mockCompanionObj)
wrapper.callCompanionMethod()
verify(mockCompanionObj).someCompanionMethod()
....
}

方案二:使用Mockk在 Mockk 中模拟伴生对象很容易。无需在源代码中插入测试接口(interface)对象。

 @Test
fun testCompanionObject() {
//Mock the companion object
mockkObject(DummyCompanion.Companion)

//define the stubbing bechavior of a companion object method
every { DummyCompanion.Companion.companionMethod() } answers { stubMethod() }

val testObject = DummyWrapper()

//Call a method that calls the companion object method
//You can verify stubMethod() is called
testObject.callCompanionMethod()

verify(exactly = 1) { DummyCompanion.someCompanionMethod() }
}

有关详细信息,请参阅 Mockk

关于java - 调用验证伴随对象方法的单元测试(模拟伴随对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com