如何使用PowerMockito模拟重载的返回void的公共静态方法

huangapple go评论104阅读模式
英文:

How to mock overloaded public static method which returns void with PowerMockito

问题

以下是您要翻译的代码部分:

我遇到了一个问题需要模拟一个返回void的公共静态方法

到目前为止我的代码如下

@RunWith(PowerMockRunner.class)
@PrepareForTest(TheUtilsClass.class)
public class MyTest {
    @Test
    public void theTest() {
        PowerMockito.mockStatic(TheUtilsClass.class);
        PowerMockito.doThrow(new RuntimeException.class).when(TheUtilsClass.class, "methodToBeMocked", any(FirstParam.class), any(SecondParam.class));
    }
}

注意:在这段代码中,有一个文本"methodToBeMocked",应该替换为"methodToBeMocked",因为它是实际的方法名称。

英文:

I got a problem mocking a public static method which returns void.

This is what I have so far:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TheUtilsClass.class)
public class MyTest {
    @Test
    public void theTest() {
        PowerMockito.mockStatic(TheUtilsClass.class);
        PowerMockito.doThrow(new RuntimeException.class).when(TheUtilsClass.class, "methodToBeMocked", any(FirstParam.class), any(SecondParam.class));
    }
}

And this does not work because "methodToBeMocked" is overloaded several times. Instead I got the exception TooManyMethodsFoundException where I could not suppress other methods.

答案1

得分: 1

我已经自己找到了解决方案,但在网上找不到。实际上,我只是创建了一个抛出所需异常的答案,就这样:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TheUtilsClass.class)
public class MyTest {
    @Test
    public void theTest() {
        PowerMockito.mockStatic(BeanUtils.class, new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                throw new RuntimeException();
            }
        });
    }
}
英文:

I have found solution myself, but could not find it online. Actually I just have created an Answer which throws the needed exception and that's it:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TheUtilsClass.class)
public class MyTest {
    @Test
    public void theTest() {
		PowerMockito.mockStatic(BeanUtils.class, new Answer&lt;Void&gt;() {
		    @Override
		    public Void answer(InvocationOnMock invocation) throws Throwable {
			    throw new RuntimeException();
		    }
        });
    }
}

huangapple
  • 本文由 发表于 2023年7月31日 22:53:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定