I have a weird test code that is always green. At the same time, one of the tests should not be green. See code below.
This is the class I need to check.
public class A {
private String param;
public void print(){
System.out.println(this.param);
}
public static void printHello(){
System.out.println("Hello!");
}
}
And check yourself
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() {
a.print();
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));
}
}
Obviously, the testStatic () method should fail because it does not call 10 times.
UPD
Here is my new test version
@PrepareForTest(A.class)
public class ATest extends PowerMockTestCase {
@Spy
private A a = new A();
@BeforeMethod
public void setUp() {
initMocks(this);
}
@Test
public void test() {
a.print();
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));
}
@ObjectFactory
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
}
And stacktrace error
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)
Aaron source
share