gpt4 book ai didi

java - 使用 powermockito 模拟静态类

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

即使我关注了 manual我似乎无法使用 PowerMock 模拟静态方法。我正在尝试模拟一个单例神类。

测试代码如下:

@RunWith(PowerMockRunner.class)
@PrepareForTest(GodClass.class)
public class SomeTestCases {
@Test
public void someTest() {
PowerMockito.mockStatic(GodClass.class);
GodClass mockGod = mock(GodClass.class);
when(GodClass.getInstance()).thenReturn(mockGod);
// Some more things mostly like:
when(mockGod.getSomethingElse()).thenReturn(mockSE);

// Also tried: but doesn't work either
// when(GodClass.getInstance().getSomethingElse()).thenReturn(mockSE);

Testee testee = new Testee(); // Class under test
}
}

和受测者:

class Testee {
public Testee() {
GodClass instance = GodClass.getInstance();
Compoment comp = instance.getSomethingElse();
}
}

但是,这不起作用。 Debug模式显示 instancenull。有什么不同之处?

(是的,我知道代码很糟糕,但它是遗留的,我们希望在重构之前进行一些单元测试)

最佳答案

我只是基本上输入了您在这里得到的内容,它对我来说工作正常。

public class GodClass
{
private static final GodClass INSTANCE = new GodClass();

private GodClass() {}

public static GodClass getInstance()
{
return INSTANCE;
}

public String sayHi()
{
return "Hi!";
}
}

public class Testee
{
private GodClass gc;
public Testee() {
gc = GodClass.getInstance();
}

public String saySomething()
{
return gc.sayHi();
}
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(GodClass.class)
public class GodClassTester
{
@Test
public void testThis()
{
PowerMockito.mockStatic(GodClass.class);
GodClass mockGod = PowerMockito.mock(GodClass.class);
PowerMockito.when(mockGod.sayHi()).thenReturn("Hi!");
PowerMockito.when(GodClass.getInstance()).thenReturn(mockGod);

Testee testee = new Testee();
assertEquals("Hi!", testee.saySomething());

}
}

关于java - 使用 powermockito 模拟静态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21048437/

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