繁体   English   中英

使用PowerMockito模拟私有方法调用返回null而不是返回List <String> :(不想执行私有方法)

[英]Mocking private method call using PowerMockito returns null instead of returning List<String>: (Want not to execute private method)

我正在尝试使用JUnit4对方法进行单元测试。 测试中的方法是调用另一个私有方法,我想使用PowerMockito来模拟它。

我的方法如下:

Class MyClass {
    public List<String> myMethod(String name) throws IOException
    {
       ... Few lines of code for setting variables
       List<String> result = myPrivateMethod(a, b);

       ... Few more lines of code..
       result.addAll(myPrivateMethod(c, d)); 

       return result;
    }

    private List<String> myPrivateMethod(String a, String b) {
    .....
    }
}

我测试上面代码的单元测试方法如下:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class TestClass {

  @Test
  public void testMyMethod() throws Exception {
    MyClass myClass = PowerMockito.spy(new MyClass());
    PowerMockito.doReturn(new ArrayList<String>(){{add("temp");}}).when(myClass, "myPrivateMethod", "a", "b");
    List<String> list = myClass.myMethod("someName");
    assertEquals(list.size(), 1);
  }
}

我期待行PowerMockito.doReturn(new ArrayList(){{add(“temp”);}})。when(myClass,“myPrivateMethod”,“a”,“b”); 返回大小为1的列表。我验证执行不会进入私有方法,但我没有获得一个值添加的List。

上面的单元测试代码有什么问题,为什么我在PowerMockito.doReturn()方法中提到null而不是填充List?

在您的测试中,您正在调用myMethod ,而myMethod又会调用myPrivateMethod两次,请参阅:

List<String> result = myPrivateMethod(a, b);
...
result.addAll(myPrivateMethod(c, d));

但是你的测试只会嘲笑myPrivateMethod所以流程如下:

  1. myMethod - > myPrivateMethod参数是a, b - 这 myPrivateMethodmyPrivateMethod返回“temp”
  2. myMethod - > myPrivateMethod ,其中参数为c, d - 这不是 myPrivateMethod ,因此myPrivateMethod被执行

为了使这个断言通过: assertEquals(list.size(), 1); 你需要重新设计你的测试以模拟对myPrivateMethod的第二次调用。 另外,对“返回null”的引用表明when块在这里: .when(myClass, "myPrivateMethod", "a", "b")myMethod提供的实际参数不匹配。

这是一个有效的例子:

public class MyClass {
    public List<String> myMethod(String name) throws IOException {
        List<String> result = myPrivateMethod("a", "b");
        result.addAll(myPrivateMethod("c", "d"));
        return result;
    }

    private List<String> myPrivateMethod(String a, String b) {
        List<String> r = new ArrayList<>();
        r.add(a);
        r.add(b);
        return r;
    }
}

@Test
public void testMyMethod() throws Exception {
    MyClass myClass = PowerMockito.spy(new MyClass());

    PowerMockito.doReturn(new ArrayList<String>(){{add("temp");}})
        .when(myClass, "myPrivateMethod", "a", "b");

    PowerMockito.doReturn(new ArrayList<String>())
        .when(myClass, "myPrivateMethod", "c", "d");

    List<String> list = myClass.myMethod("someName");
    assertEquals(1, list.size());
    assertEquals("temp", list.get(0));
}

上面的示例测试通过以下内容:

  • junit:4.12
  • powermock-module-junit4:2.0.2
  • powermock-api-mockito2:2.0.2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM