gpt4 book ai didi

mockito - 使用 mockito-inline 库在本地创建的对象上的模拟方法调用

转载 作者:行者123 更新时间:2023-12-04 08:13:29 33 4
gpt4 key购买 nike

为了模拟在被测方法内部构造的本地对象上的局部变量/方法调用,我们目前使用的是 PowerMockito 库。
我们正在尝试评估是否可以使用 mockito-inline(版本 3.7.7)来做同样的事情。
简而言之,我们正在尝试使用 Mockito.mockConstruction 拦截对象的构造,以便我们可以在本地创建的对象上指定模拟行为。
这是一个场景,描述了我们的用法。由于这是遗留代码,我们现在无法更改它。(例如,更改对实例变量的依赖或其他一些重构)
简而言之,MyClass 类的execute() 方法是在本地构造Util 类的对象。由于我们要对 execute() 的核心逻辑进行单元测试,因此需要模拟在 MyClass 类的 execute() 方法中创建的本地 Util 对象上调用的 process() 方法。

public class MyClass {

public String execute(){

Util localUtil = new Util();
String data = localUtil.process();

//Core logic of the execute() method that needs to be unit tested...
//Further update data based on logic define in process() method.
data = data + " core logic";

return data;
}
}

public class Util {
public String process(){
String result = "real";
//Use various other objects to arrive at result
return result;
}
}

@Test
public void testLocalVar(){

Util util = new Util();
Assertions.assertEquals("real", util.process());

try (MockedConstruction<Util> mockedConstruction = Mockito.mockConstruction(Util.class);) {

util = new Util();
when(util.process()).thenReturn("mocked method data");
String actualData = util.process();

//This works on local object created here.
Assertions.assertEquals("mocked method data",actualData);

//Object,method under test
MyClass myClass = new MyClass();
actualData = myClass.execute();
//This doesn't not works on local object created inside method under test
Assertions.assertEquals("mocked method data" + " core logic",actualData); //Fails

}
}
在这里,我们能够在测试方法中本地创建的对象上的方法上定义模拟行为。但是对于在测试的实际方法中创建的本地对象,同样的事情是不可能的。
我可以看到 mockedConstruction.constructed() 确实创建了类的每个对象
但无法在 execute() 方法中的 localUtil.process() 上指定模拟行为..
有什么建议..

最佳答案

在您的情况下,您必须在指示 Mockito 模拟构造函数时 stub 该行为。 Mockito.mockConstruction()被重载并且不仅允许传递您想要模拟构造函数的类:

@Test
void mockObjectConstruction() {
try (MockedConstruction<Util> mocked = Mockito.mockConstruction(Util.class,
(mock, context) -> {
// further stubbings ...
when(mock.process()).thenReturn("mocked method data");
})) {

MyClass myClass = new MyClass();
actualData = myClass.execute();
}
}
您可以在此 article 中找到更多可能的 stub 场景。 .

关于mockito - 使用 mockito-inline 库在本地创建的对象上的模拟方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65832174/

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