Java Powermockito doNothing 用于带参数的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22981048/
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-13 19:45:21  来源:igfitidea点击:

Powermockito doNothing for method with arguments

javaunit-testingpowermock

提问by Anakin001

I've developed an application in Java and I'm trying to create unit tests using Powermockito (I should add that I'm new to unit testing).

我已经用 Java 开发了一个应用程序,我正在尝试使用 Powermockito 创建单元测试(我应该补充一点,我是单元测试的新手)。

I have a class called Resource which has a static method called readResources:

我有一个名为 Resource 的类,它有一个名为 readResources 的静态方法:

public static void readResources(ResourcesElement resourcesElement);

ResourcesElement is also coded by me. In testing, I want to create my own Resource, so I want the above method to do nothing. I tried using this code:

ResourcesElement 也是我编码的。在测试中,我想创建自己的Resource,所以我希望上面的方法什么都不做。我尝试使用此代码:

    PowerMockito.spy(Resource.class);
    PowerMockito.doNothing().when(Resource.class, "readResources", Matchers.any(ResourcesElement.class));

The unit test throws an exception:

单元测试抛出异常:

org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here: -> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)

org.mockito.exceptions.misusing.UnfinishedStubingException:在此处检测到未完成的存根:-> 在 org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)

Powermockito also suggest that I should use thenReturn or thenThrow after when, but it seems that the method 'when' returns void when it is called after doNothing (which is logical). If I try:

Powermockito 还建议我应该在 when 之后使用 thenReturn 或 thenThrow,但似乎方法 'when' 在 doNothing 之后调用时返回 void(这是合乎逻辑的)。如果我尝试:

PowerMockito.when(Resource.class, "readResources", Matchers.any(ResourcesElement.class)).....

doNothing is not an option after when.

doNothing 不是什么时候之后的选项。

I managed to make methods without arguments to do nothing, using the 2 arguments version of the method. For example:

我设法使没有参数的方法什么都不做,使用该方法的 2 个参数版本。例如:

PowerMockito.doNothing().when(Moduler.class, "startProcessing");

This works (startProcessing doesn't take any arguments).

这有效(startProcessing 不带任何参数)。

But how can I make methods that do take arguments to do nothing with Powermockito?

但是我怎样才能制作出接受参数而对 Powermockito 不做任何事情的方法呢?

采纳答案by Morfic

You can find a fully functional example below. Since you didn't post the complete example, I can only assume that you did not annotate the test class with @RunWithor @PrepareForTestbecause the rest seems fine.

您可以在下面找到一个功能齐全的示例。由于您没有发布完整的示例,我只能假设您没有使用@RunWith@PrepareForTest因为其余部分看起来不错而没有对测试类进行注释。

@RunWith(PowerMockRunner.class)
@PrepareForTest({Resource.class})
public class MockingTest{

    @Test
    public void shouldMockVoidStaticMethod() throws Exception {
        PowerMockito.spy(Resource.class);
        PowerMockito.doNothing().when(Resource.class, "readResources", Mockito.any(String.class));

        //no exception heeeeere!
        Resource.readResources("whatever");

        PowerMockito.verifyStatic();
        Resource.readResources("whatever");
    }

}

class Resource {
    public static void readResources(String someArgument) {
        throw new UnsupportedOperationException("meh!");
    }
}

回答by ZaoTaoBao

Maybe i can't undestand your question, but i believe it's necessary specify what must do the method, so if you don't specify thenReturn or thenThrow or whatever powerMockito doesn't know what have to do when read your real code, for example:

也许我无法理解您的问题,但我认为有必要指定必须执行该方法的内容,因此,如果您不指定 thenReturn 或 thenThrow 或任何 powerMockito 在阅读您的真实代码时不知道必须做什么,例如:

REAL CODE:

真实代码:

            IPager pag;
        IPagerData<List<IDeute>> dpag;
        pag = new PagerImpl();
        pag.setFiles(nombrefilesPaginador);
        pag.setInici(1);
        dpag = gptService.obtenirDeutes(idSubjecte, idEns, tipusDeute, periode, pag);

Testing real code by mockito:

通过 mockito 测试真实代码:

        IPager pag = new PagerImpl();
        pag.setInici(1);
        pag.setFiles(0);
        when(serveiGpt.obtenirDeutes(eq(331225L),
         eq(IConstantsIdentificadors.ID_ENS_BASE), 
         Matchers.any(ETipusDeute.class),
         Matchers.any(EPeriodeDeute.class), 
         eq(pag)))
        .thenThrow(new NullPointerException(" Null!"));

If haven't specify the return my test will be fail. I hope it helps.

如果没有指定返回我的测试将失败。我希望它有帮助。

回答by Walls

If doNothing()isn't working you can hack it a bit using the PowerMockito.doAnswer(). This lets you mock into void methods that are supposed to do something, like setting values, etc. If doNothing()doesn't work, using a blank doAnswer()should work fine.

如果doNothing()不起作用,您可以使用PowerMockito.doAnswer(). 这使您可以模拟应该执行某些操作的 void 方法,例如设置值等。如果doNothing()不起作用,则使用空白doAnswer()应该可以正常工作。

Example:

例子:

PowerMockito.doAnswer(new org.mockito.stubbing.Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return null; //does nothing
    }
}).when(mockObject).methodYouWantToDoNothing(args);

回答by Aniket Thakur

Why go through so much trouble just so that your method does not do anything. Just calling PowerMockito.mockStatic(Resource.class)should replace all static methods in your class with default stubs which basically mean they do nothing.

为什么要经历这么多的麻烦,以至于你的方法没有做任何事情。只是调用PowerMockito.mockStatic(Resource.class)应该用默认存根替换类中的所有静态方法,这基本上意味着它们什么都不做。

Unless you do want to change the behavior of your method to actually do something just calling PowerMockito.mockStatic(Resource.class)should suffice. Ofcourse this also means all static methods in the class are stubbed which you need to consider.

除非您确实想更改方法的行为以实际执行某些操作,否则调用PowerMockito.mockStatic(Resource.class)就足够了。当然,这也意味着类中的所有静态方法都需要考虑。