使用 PowerMockito 1.6 验证静态方法调用
Verify Static Method Call using PowerMockito 1.6
我正在为类似于下面给出的示例的方法编写 JUnit 测试用例:
Class SampleA{
public static void methodA(){
boolean isSuccessful = methodB();
if(isSuccessful){
SampleB.methodC();
}
}
public static boolean methodB(){
//some logic
return true;
}
}
Class SampleB{
public static void methodC(){
return;
}
}
我在测试中写了下面的测试用例class:
@Test
public void testMethodA_1(){
PowerMockito.mockStatic(SampleA.class,SampleB.class);
PowerMockito.when(SampleA.methodB()).thenReturn(true);
PowerMockito.doNothing().when(SampleB.class,"methodC");
PowerMockito.doCallRealMethod().when(SampleA.class,"methodA");
SampleA.methodA();
}
现在我想验证 class 示例 B 的静态方法 C() 是否被调用。如何使用 PowerMockito 1.6 实现?我已经尝试了很多东西,但它似乎并不适合我。感谢任何帮助。
就我个人而言,我不得不说 PowerMock 等是解决一个问题的方法,如果你的代码不错的话,你不应该有这个问题。在某些情况下,它是必需的,因为框架等使用静态方法导致无法以其他方式测试代码,但如果它是关于您的代码,您应该始终更喜欢重构而不是静态模拟。
无论如何,在 PowerMockito 中验证应该不会那么难...
PowerMockito.verifyStatic( Mockito.times(1)); // Verify that the following mock method was called exactly 1 time
SampleB.methodC();
(当然,要使其工作,您必须将 SampleB 添加到 @PrepareForTest
注释并为其调用 mockStatic
。)
我正在为类似于下面给出的示例的方法编写 JUnit 测试用例:
Class SampleA{
public static void methodA(){
boolean isSuccessful = methodB();
if(isSuccessful){
SampleB.methodC();
}
}
public static boolean methodB(){
//some logic
return true;
}
}
Class SampleB{
public static void methodC(){
return;
}
}
我在测试中写了下面的测试用例class:
@Test
public void testMethodA_1(){
PowerMockito.mockStatic(SampleA.class,SampleB.class);
PowerMockito.when(SampleA.methodB()).thenReturn(true);
PowerMockito.doNothing().when(SampleB.class,"methodC");
PowerMockito.doCallRealMethod().when(SampleA.class,"methodA");
SampleA.methodA();
}
现在我想验证 class 示例 B 的静态方法 C() 是否被调用。如何使用 PowerMockito 1.6 实现?我已经尝试了很多东西,但它似乎并不适合我。感谢任何帮助。
就我个人而言,我不得不说 PowerMock 等是解决一个问题的方法,如果你的代码不错的话,你不应该有这个问题。在某些情况下,它是必需的,因为框架等使用静态方法导致无法以其他方式测试代码,但如果它是关于您的代码,您应该始终更喜欢重构而不是静态模拟。
无论如何,在 PowerMockito 中验证应该不会那么难...
PowerMockito.verifyStatic( Mockito.times(1)); // Verify that the following mock method was called exactly 1 time
SampleB.methodC();
(当然,要使其工作,您必须将 SampleB 添加到 @PrepareForTest
注释并为其调用 mockStatic
。)