PowerMockito.verifyStatic() Problems

John A Qualls picture John A Qualls · Oct 6, 2015 · Viewed 30.9k times · Source

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

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.

Test Class:

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();
    }
}

Class Under Test:

public class Test1 {
    public static void staticMethod() {
        System.out.println("Static Method!");
    }
}

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!

Answer

John A Qualls picture John A Qualls · Oct 7, 2015

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();
    }
}

After the static method is invoked, you need to verify that it was called by calling it again after your verifyStatic() call.

i.e.

        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();