【问题标题】:Testing private method using power mock which return list of Integers使用返回整数列表的 power mock 测试私有方法
【发布时间】:2011-10-29 14:50:31
【问题描述】:

我有一个私有方法,它采用整数值列表返回整数值列表。我如何使用 power mock 来测试它。我是 powermock 的新手。我可以用简单的模拟进行测试吗..?怎么样..

【问题讨论】:

  • 我认为,如果您提供一个具体示例说明您尝试过的方法和无效的方法,您会获得更多帮助。

标签: java easymock powermock


【解决方案1】:

来自the documentation,在名为“通用 - 绕过封装”的部分中:

使用 Whitebox.invokeMethod(..) 调用一个私有方法 实例或类。

您还可以在同一部分中找到示例。

【讨论】:

  • 链接已失效
【解决方案2】:

这是一个完整的例子:

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.powermock.reflect.Whitebox;

class TestClass {
    private List<Integer> methodCall(int num) {
        System.out.println("Call methodCall num: " + num);
        List<Integer> result = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            result.add(new Integer(i));
        }
        return result;
    }
}

 @Test
 public void testPrivateMethodCall() throws Exception {
     int n = 10;
     List result = Whitebox.invokeMethod(new TestClass(), "methodCall", n);
     Assert.assertEquals(n, result.size());
 }

【讨论】:

    【解决方案3】:
    Whitebox.invokeMethod(myClassToBeTestedInstance, "theMethodToTest", expectedFooValue);
    

    【讨论】:

    • 我发现需要使用类实例而不是类对象。 (即 myClassToBeTestedInstance 而不是 ClassToBeTested.class)
    【解决方案4】:

    当你想用 Powermockito 测试一个私有方法并且这个私有方法有语法时:

    private int/void testmeMethod(CustomClass[] params){
    ....
    }
    

    在您的测试类方法中:

    CustomClass[] 参数= new CustomClass[] {...} WhiteboxImpl.invokeMethod(spy,"testmeMethod",params)

    由于参数而无法工作。您收到一条错误消息,表明带有该参数的 testmeMethod 不存在 看这里:

    WhiteboxImpl 类

    public static synchronized <T> T invokeMethod(Object tested, String methodToExecute, Object... arguments)
                throws Exception {
            return (T) doInvokeMethod(tested, null, methodToExecute, arguments);
        }
    

    对于 Array 类型的参数,PowerMock 搞砸了。因此,在您的测试方法中将其修改为:

    WhiteboxImpl.invokeMethod(spy,"testmeMethod",(Object) params)
    

    对于无参数的私有方法,你没有这个问题。我记得它适用于 Primitve 类型和包装类的参数。

    “理解 TDD 就是理解软件工程”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2016-04-10
      • 2018-04-09
      相关资源
      最近更新 更多