我有一段奇怪的测试代码,总是绿色的。但其中一个测试不应该是绿色的。请看下面的代码。
这是我需要测试的类:
public class A {
private String param;
public void print(){
System.out.println(this.param);
}
public static void printHello(){
System.out.println("Hello!");
}
}
测试自身
import org.mockito.Spy;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
import static org.powermock.reflect.Whitebox.invokeMethod;
public class ATest {
@Spy
private A a = new A();
@BeforeMethod
public void setUp() {
initMocks(this);
}
@Test
public void test() {
// When
a.print();
// Than
verify(a, times(1)).print();
}
@Test
@PrepareForTest(A.class)
public void testStatic() throws Exception {
mockStatic(A.class);
replay();
invokeMethod(A.class, "printHello");
verifyStatic(times(10)); // must be fail
}
}
显然,testStatic() 方法应该失败,因为它没有被调用10次。
更新:这是我的新版本测试。
@PrepareForTest(A.class)
public class ATest extends PowerMockTestCase {
@Spy
private A a = new A();
@BeforeMethod
public void setUp() {
initMocks(this);
}
@Test
public void test() {
// When
a.print();
// Than
verify(a, times(1)).print();
}
@Test
@PrepareForTest(A.class)
public void testStatic() throws Exception {
mockStatic(A.class);
replay();
invokeMethod(A.class, "printHello");
verifyStatic(times(10)); // must be fail
}
@ObjectFactory
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
}
错误堆栈信息
org.mockito.exceptions.verification.TooManyActualInvocations:
a.print();
Wanted 1 time:
-> at com.aaron.simple.ATest.test(ATest.java:37)
But was 2 times. Undesired invocation:
-> at com.aaron.simple.ATest.test(ATest.java:34)
@RunWith(PowerMockRunner.class)
。 - blgt@ObjectFactory
:更多信息在此处。这是TestNG中与JUnit中的@RunWith
所做的相当的东西。 - blgt