gpt4 book ai didi

java - 静态实例上的模拟方法

转载 作者:行者123 更新时间:2023-11-30 06:25:29 24 4
gpt4 key购买 nike

我有一个类:

public class Factory {
private static final Factory instance = new Factory();
private Factory() {
}
public static Factory getInstance() {
return instance;
}
private Client client = null;

//To be mocked
//Failing at this point
//Not actually using mocked method
public Client getClient(Properties properties) {
//doSomething
//...
return client;
}
}

在另一个类中,上述方法用作:

public class Service {
protected Client client = null;
protected void keySetup() {
//Should be mocked
client = Factory.getInstance().getClient(properties());

...
...
}
}

对于 keySetup() 方法的单元测试,我尝试模拟 Factory.getInstance().getClient(properties()) 但失败了。

我尝试执行以下操作:

@Test
public void testKeySetupTrue(){
Client client = mock(Client.class);
Factory factory = mock(Factory.class);
ReflectionTestUtils.setField(factory, "client", client);
Properties properties = mock(Properties.class);

Mockito.doReturn(client).when(factory)
.getClient(properties);

Service service = new Service();

service.keySetup();
...
...
}

当我在 Debug模式下运行时,我看到它实际上正在执行被模拟的 getClient(Properties properties)

如何解决这个问题?

最佳答案

static final 不是一个很好的设计。最好注入(inject)依赖项并让框架(spring 或其他)担心控制单例。也就是说,就你而言,使用反射通过模拟工厂设置 Factory 实例 变量。

关于java - 静态实例上的模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47289612/

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