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

标签 java class reflection mockito

我有一个名为 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/

相关文章:

java - 如何将 JTextField[][] 作为参数传递给动态加载的 java 类方法?

reflection - 如何反射(reflect)Golang中对象的动态方法名

java - List中有没有一种reverse_iterator,只是为了反转List? (首选Java8流方案)

python - 为什么这个类的构造函数会引发这个错误?

c++ - 使用指向类成员和结构成员的指针之间的差异

javascript - 如何将使用 "this"关键字的函数传递到 JavaScript 类中?

java - 遍历对象层次结构

java.lang.runtimeException : unable to start activity componentinfo{}: java. lang.nullpointerException

java - Android - 如何从 Web 浏览器与 Android 应用程序交互?

java - 重新触发 MouseListener 事件