如何解决Powermock 在模拟私有方法时抛出 InvalidUseOfMatchersException
我是 Powermock 的新手。昨天我看了一个关于使用 Powermock 的视频,我遵循了他们的代码并在下面有一个演示测试程序。当我运行测试
package myPackage;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class Test1{
@Test
public void testPrivateMethod() throws Exception {
DemoService mockDemoService = PowerMockito.spy(new DemoService());
PowerMockito.when(
mockDemoService,"privateMethod",ArgumentMatchers.any(String.class)
).then(invocation -> invocation.getArgument(0) + "_private_mock");
Assert.assertEquals(mockDemoService.dependentMethod("LoveTest"),"3000LoveTest_private_mock");
}
}
class DemoService {
private String privateMethod(String input) {
return input + "_private";
}
public String dependentMethod(String input) {
return 3000 + privateMethod(input);
}
}
它在下面的日志中抛出异常
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at myPackage.Test1.testPrivateMethod(Test1.java:19)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument,in this case,use primitive alternatives.
when(mock.get(any())); // bad use,will raise NPE
when(mock.get(anyInt())); // correct usage use
Also,this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
我对 Mockito 有一些基本的了解,代码有点类似于 Mockito 单元测试(Mockito.spy 和 Mockito.when),但没有按预期工作。不知道代码有什么问题,为什么抛出异常InvalidUseOfMatchersException。请帮帮我,谢谢。
解决方法
您的代码缺少@PrepareForTest。 Powermock 必须操作目标模拟类的字节码,因此您必须提供它的路径。
@RunWith(PowerMockRunner.class)
@PrepareForTest(DemoService.class)
public class Test1{
...
,
这里 ArgumentMatchers.any(String.class) 而是使用 ArgumentMatchers.anyString()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。