gpt4 book ai didi

java - 如何在动态加载的 jar 中模拟方法

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

我有一个名为 Price 的类,带有构造函数,我通过反射动态加载它:

public Price(Context context, String pair) {
this.context = context;
this.value1 = pair.substring(0, 3);
this.value2 = pair.substring(3, 6);
this.dps = context.getService().getm1(value1, value2).getm2();
}

但是我想模拟 Context 对象

我想要

context.getService().getm1(value1, value2).getm2()

返回 5。

这是我尝试过的

//mocking the Context class
Class<?> contextClass = urlClassLoader.loadClass("com.algo.Context");
constructor =contextClass.getConstructor();
Object context = Mockito.mock(contextClass);

//trying to instantiate the Price class
Class<?> priceClass = urlClassLoader.loadClass("com.algo.Price");
constructor = priceClass.getConstructor(contextClass,String.class);
Mockito.when(context.getService().getm1(value1, value2).getm2().thenReturn(5));
Object price = constructor.newInstance(context,"PRICES");

但是我下面有一条红线

context.getService()

错误提示

The method getService() is undefined for the type Object

如何解决这个问题,我的最终目标是使用变量创建 Price 对象

dps

作为一个 int 5,这就是为什么我想模拟 Context 对象。

最佳答案

对我来说,唯一的方法是使用反射来实现整个测试,这确实很费力,特别是在您的情况下,因为您需要为每个方法调用执行相同的操作,因为您无法直接模拟 context.getService() .getm1(value1, value2).getm2().

假设我有一个类 Context 如下

public class Context {

public int getm1(String value1, String value2) {
return -1;
}
}

正常的测试用例是:

@Test
public void normal() throws Exception {
Context context = Mockito.mock(Context.class);
Mockito.when(context.getm1(Mockito.anyString(), Mockito.anyString())).thenReturn(5);
Assert.assertEquals(5, context.getm1("foo", "bar"));
}

使用反射的相同测试将是:

@Test
public void reflection() throws Exception {
... // Here I get the classloader
// Get the class by reflection
Class<?> contextClass = urlClassLoader.loadClass("com.algo.Context");
// Mock the class
Object context = Mockito.mock(contextClass);
// Get the method by reflection
Method method = contextClass.getMethod("getm1", String.class, String.class);
// Invoke the method with Mockito.anyString() as parameter
// to get the corresponding methodCall object
Object methodCall = method.invoke(context, Mockito.anyString(), Mockito.anyString());
// Mock the method call to get what we expect
Mockito.when(methodCall).thenReturn(5);
// Test the method with some random values by reflection
Assert.assertEquals(5, method.invoke(context, "foo", "bar"));
}

关于java - 如何在动态加载的 jar 中模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536371/

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