我有一个具有两个静态方法的工具类,即dosomething(object)和calldosomething()。名称是直观的,因为CallDosothing会委托其呼叫dosomething(object);
public class Tool
{
public static void doSomething( Object o )
{
}
public static void callDoSomething()
{
doSomething( new Object());
}
}
我有一个用于工具的测试类,我想验证是否调用了dosomething(对象)(我想在以后也匹配参数)
@RunWith( PowerMockRunner.class )
@PrepareForTest( { Tool.class } )
public class ToolTest
{
@Test
public void toolTest()
{
PowerMockito.mockStatic( Tool.class );
Tool.callDoSomething();// error!!
//Tool.doSomething();// this works! it gets verified!
PowerMockito.verifyStatic();
Tool.doSomething( Mockito.argThat( new MyArgMatcher() ) );
}
class MyArgMatcher extends ArgumentMatcher<Object>
{
@Override
public boolean matches( Object argument )
{
return true;
}
}
}
如果直接调用,请验证拾起dosomething(对象)。我已经在上面评论了此代码。使用CallDosomething(这是上面显示的代码)时,验证不会在使用dosomething(对象)。这是运行上述代码时的错误日志:
Wanted but not invoked tool.doSomething(null);
However, there were other interactions with this mock.
at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.performIntercept(MockitoMethodInvocationControl.java:260)
at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.invoke(MockitoMethodInvocationControl.java:192)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:105)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:60)
at Tool.doSomething(Tool.java)
at ToolTest.toolTest(ToolTest.java:22)
... [truncated]
我想避免对工具类进行任何更改。我的问题是,如何从calldosomething()调用dosomething(对象),并在Dosomething的param
听起来您想使用静态间谍(部分模拟)。关于嘲笑静态的PowerMock文档的部分在第二个子弹中有一个很容易错过的注释:
(使用powermockito.spy(类)模拟特定方法)
注意,在您的示例中,您实际上并没有嘲笑行为,只是验证该方法被调用。有一个微妙但重要的区别。如果您不希望doSomething(Object)
被调用,则需要做类似的事情:
@Test
public void toolTest() {
PowerMockito.spy(Tool.class); //This will call real methods by default.
//This will suppress the method call.
PowerMockito.doNothing().when(Tool.class);
Tool.doSomething(Mockito.argThat( new MyArgMatcher() ));
Tool.callDoSomething();
//The rest isn't needed since you're already mocking the behavior
//but you can still leave it in if you'd like.
PowerMockito.verifyStatic();
Tool.doSomething(Mockito.argThat( new MyArgMatcher() ));
}
,如果您仍然希望该方法发射,只需删除doNothing()
的两行即可。(我在我的tool.java版本中添加了一个简单的 System.out.println("do something " + o);
,作为doNothing()
的附加验证。)
您可以对此进行验证:
public class Tool{
public static boolean isFromCallDoSomethingMethod= false;
public static void doSomething(Object o){
}
public static void callDoSomething() {
doSomething(new Object());
isFromCallDoSomethingMethod= true;
}
}
您可以进行验证:
if(Tool.isFromCallDoSomethingMethod){
//you called doSomething() from callDoSomething();
}
记住
如果您从callDoSomething()
的另一种方式调用doSomething()
,请不要忘记进行验证,您可以通过使用Tool.isFromCallDoSomethingMethod = false
这是您想要的吗?