gpt4 book ai didi

java - Mockito - 模拟库调用

转载 作者:行者123 更新时间:2023-11-30 05:47:33 31 4
gpt4 key购买 nike

我有以下结构

public class classAImpl implements classA {

public ClassC getTarget(Classc cObj) {
// library call
RegistryLib.init();
// some more code to construct cObj with more info
return cObj
}
}

// Registry Library Class
Class RegistryLibClass{
public void init() {
ClassD.builder.build();
}
}

我的测试类正在尝试测试调用上面编写的 getTarget() 方法的方法。我想完全避免执行 getTarget() 方法,即使在模拟它之后我也无法执行该方法。到目前为止,我已经尝试过以下方法:

Class Testclass {
@Before
public void setUp() {
Testclass mock = PowerMockito.mock(Testclass.class);
PowerMockito.when(mock.getTarget(cObj)).thenReturn(cObj);
}

private ClassC getTarget(cObj) {
return cObj;
}
}

感谢任何帮助!

最佳答案

假设您想测试 B 类 中从 A 类 调用 getTarget 的方法,您可以这样做,

B b = new B();
A a = Mockito.mock(A.class);
C c = new C();
Mockito.when(a.getTarget(Mockito.any(C.class)).thenReturn(c);
boolean isPresent = b.someMethodToTest();
assertEquals("someMethodToTest was supposed to return true", true/*expected*/, isPresent);

编辑#1您需要使用 Powermockito 来模拟静态方法,以不返回任何内容,如上所述 here

@PrepareForTest(RegistryLibClass.class) //at the top of the class

//inside your test
PowerMockito.mockStatic(RegistryLibClass.class);
Mockito.when(RegistryLibClass.init()).doNothing();

关于java - Mockito - 模拟库调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54582963/

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