PowerMockito.verifyStatic()问题 [英] PowerMockito.verifyStatic() Problems
问题描述
我需要使用PowerMockito来测试是否调用了特定的静态方法.我正在使用以下PowerMockito和JUnit库...
I need to use PowerMockito to test if a specific static method is called. I am using the following PowerMockito and JUnit libraries ...
- powermock-mockito-1.6.2-full.jar
- junit-4.12.jar
我在使PowerMockito.verifyStatic()方法正常工作时遇到问题.在下面的代码示例中,我尝试使用@PrepareForTest和嘲笑Static(),并尝试排除它们.在代码示例中,我包括了它们.
I am having issues getting the PowerMockito.verifyStatic() method to work properly. In the following code example, I have tried using the @PrepareForTest, and mockStatic(), and I have tried excluding them. In the code example I include them.
测试类:
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Test1.class)
public class PowerMockTest {
@Test
public void staticVerifyTest() {
PowerMockito.mockStatic(Test1.class);
// Test
PowerMockito.verifyStatic();
//Test1.staticMethod();
}
}
被测类:
public class Test1 {
public static void staticMethod() {
System.out.println("Static Method!");
}
}
该测试在运行时通过,但由于从未调用Test1.staticMethod()而应失败.在这方面的任何帮助将不胜感激!
The test passes when it is run, but it should fail because Test1.staticMethod() is never called. Any help on this would be greatly appreciated!
推荐答案
Alright, I figured it out thanks to Stefan Birkner's reference
这是我的示例代码的更正:
Here is the correction to my sample code:
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Test1.class)
public class PowerMockTest {
@Test
public void staticVerifyTest() {
PowerMockito.mockStatic(Test1.class);
// Test
Test1.staticMethod();
PowerMockito.verifyStatic();
Test1.staticMethod();
}
}
调用静态方法后,您需要通过在verifyStatic()调用之后再次调用它来验证它是否已被调用.
After the static method is invoked, you need to verify that it was called by calling it again after your verifyStatic() call.
即
Test1.staticMethod();
PowerMockito.verifyStatic();
Test1.staticMethod();
您还可以像这样多次检查它是否被调用...
You can also check if it was called multiple times like this...
Test1.staticMethod();
Test1.staticMethod();
Test1.staticMethod();
PowerMockito.verifyStatic(Mockito.times(3));
Test1.staticMethod();
这篇关于PowerMockito.verifyStatic()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!