Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify Static Method Call using PowerMockito 1.6

I am writing JUnit test case for methods similar to sample given below:

Class SampleA{
    public static void methodA(){
        boolean isSuccessful = methodB();
        if(isSuccessful){
            SampleB.methodC();
        }
    }

    public static boolean methodB(){
        //some logic
        return true;
    }
}

Class SampleB{
    public static void methodC(){
        return;
    }
}

I wrote the following test case in my test class:

@Test
public void testMethodA_1(){
    PowerMockito.mockStatic(SampleA.class,SampleB.class);

    PowerMockito.when(SampleA.methodB()).thenReturn(true);
    PowerMockito.doNothing().when(SampleB.class,"methodC");

    PowerMockito.doCallRealMethod().when(SampleA.class,"methodA");
    SampleA.methodA();
}

Now I want to verify whether static methodC() of class Sample B is called or not. How can I achieve using PowerMockito 1.6? I have tried many things but it doesn't seems to be working out for me. Any help is appreciated.

like image 351
Prerak Tiwari Avatar asked Dec 16 '15 23:12

Prerak Tiwari


People also ask

How do you use PowerMockito?

Step 1: Create a class that contains a private method. We have created class with the name Utility and defined a private method and a public method (that returns the object of private method). Step 2: Create a JUnit test case named PowerMock_test for testing purpose.

What does PowerMockito mockStatic do?

You need to use the PowerMockito. mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.


1 Answers

Personally, I have to say that PowerMock, etc. is the solution to a problem that you shouldn't have if your code wasn't bad. In some cases, it is required because frameworks, etc. use static methods that lead to code that simply cannot be tested otherwise, but if it's about YOUR code, you should always prefer refactoring instead of static mocking.

Anyway, verifing that in PowerMockito shouldn't be that hard...

PowerMockito.verifyStatic( Mockito.times(1)); // Verify that the following mock method was called exactly 1 time
SampleB.methodC();

(Of course, for this to work you must add SampleB to the @PrepareForTest annotation and call mockStatic for it.)

like image 192
Florian Schaetz Avatar answered Oct 06 '22 23:10

Florian Schaetz