Java Mockito / Powermockito 模拟私有无效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25020277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:27:03  来源:igfitidea点击:

Mockito / Powermockito mock private void method

javaunit-testingmockitopowermock

提问by Mat

I need to mock a private void method which takes no arguments using mockito and powermock.

我需要使用 mockito 和 powermock 模拟一个不带参数的私有 void 方法。

The method belongs to a instance which is a spy.

该方法属于一个间谍实例。

I am aware the fact I need to do this suggests bad code but I am working with an old project converting the unit tests from one testing framework to another.

我知道我需要这样做的事实表明代码不好,但我正在处理一个旧项目,将单元测试从一个测试框架转换为另一个。

If anyone has any suggestions it would be much appreciated.

如果有人有任何建议,将不胜感激。

Thank You!

谢谢你!

So far I have tried this:

到目前为止,我已经尝试过这个:

PowerMockito.doNothing().when(Whitebox.invokeMethod(spy,"method",null));

But I get this error:

但我收到此错误:

No method found with name 'method' with parameter types: [ <none> ] 

采纳答案by Tobb

I haven't tried Whitebox (which comes with Powermock), but try something like:

我还没有尝试过 Whitebox(随 Powermock 一起提供),但可以尝试以下操作:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
    private MyClass myClass;

    @Before
    public void setup() {
        myClass = PowerMockito.spy(new MyClass());
        PowerMockito.doNothing().when(myClass, "myPrivateMethod");
    }
    //Tests..
}

.. as far as I can remember..

..据我所知..