gpt4 book ai didi

java - PowerMockito : mocking private method and get a value without accessing it

转载 作者:行者123 更新时间:2023-12-01 07:26:01 25 4
gpt4 key购买 nike

我正在为遗留代码编写java单元测试,而且我也是这个领域的新手。我必须测试以下场景(为 testableMethod() 编写单元测试用例)。因此,在 getMode() 方法中不执行代码,我想获取 mode 变量的值。

Class A{

public boolean testableMethod()
{
//code
......
int mode = getMode();
......
//do something with mode
return X;
}

private int getMode()
{
return ComplexCalls(ComplexMethodCalls(), more());
}

}

我尝试使用 PowerMockito 来完成此操作,但没有成功。可以使用 PowerMockito 模拟此类场景吗?

最佳答案

您可以使用PowerMockito spy :

public class A {
public boolean testableMethod() {
return getMode() == 1;
}

private int getMode() {
return 5;
}
}
<小时/>
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.spy;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class ATest {
@Test
public void testableMethod_should_do_this() throws Exception {
A a = spy(new A());

doReturn(1).when(a, "getMode");

assertTrue(a.testableMethod());
}
}

查看所有这些full example of partial mocking of a private method

关于java - PowerMockito : mocking private method and get a value without accessing it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24573988/

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