Testing a static method call using PowerMockito 1.6

I am writing a JUnit test case for methods similar to the examples 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; } } 

In the test class, I wrote the following test case:

 @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 check if the static method C () of the Sample B class is called or not. How can I achieve the use of PowerMockito 1.6? I have tried many things, but it seems to me that this does not work. Any help is appreciated.

+4
junit4 mockito powermock powermockito
source share
1 answer

Personally, I have to say that PowerMock, etc. is a solution to a problem that should not be if your code was not bad. In some cases this is necessary because frameworks, etc. They use static methods that lead to code that simply cannot be tested otherwise, but if it concerns YOUR code, you should always prefer refactoring instead of static mockery.

In any case, checking that in PowerMockito should not be so difficult ...

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

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

+12
source share

All Articles