How To Spy and Verify a Static Void Method in Java

The Mockito and PowerMockito libraries for JUnit4 are not always the most intuitive.

Following is an example of how to spy and verify a static void method.

    public void testAdd() {

        // Prepare the Utils class to be spied.

        // Run the test and get the actual value from the OUT
        int actualValue = App.add("Test1", 1, 1);

         * To verify the number of times that we called Utils.doSomething we
         * first need to tell the PowerMockito library which class we are
         * verifying and how many times we are verifying that action.
        PowerMockito.verifyStatic(Utils.class, Mockito.times(1));

         * Then, and this is not at all intuitive, we have to call the method
         * ourselves with the same parameters that we are expecting to have been
         * called. This tells PowerMockito which method invocation is to be
         * verified.
        Utils.doSomething(Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt());

        assertEquals(2, actualValue);

The complete example can be found here.

Leave a Reply