Search code examples
unit-testingmockitostatic-methodsfinal

How do I mock a static method in final class


I have some code that has a static method inside a final class. I was trying to mock that method. I have tried doing a few things..

public final Class Class1{

 public static void doSomething(){
  } 
}

How can I mock doSomething()? I have tried..

Class1 c1=PowerMockito.mock(Class1.class)
PowerMockito.mockSatic(Class1.class);
Mockito.doNothing().when(c1).doSomething();

This gives me an error:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at com.cerner.devcenter.wag.textHandler.AssessmentFactory_Test.testGetGradeReport_HTMLAssessment(AssessmentFactory_Test.java:63)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!

    at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.performIntercept(MockitoMethodInvocationControl.java:260)

Solution

  • Most used testing framework is JUnit 4. So if you are using it you need to annotate test class with:

    @RunWith( PowerMockRunner.class )
    @PrepareForTest( Class1.class )
    

    Than

    PowerMockito.mockSatic(Class1.class);
    Mockito.doNothing().when(c1).doSomething();
    
    Mockito.when(Class1.doSomething()).thenReturn(fakedValue);
    
    // call of static method is required to mock it
    PowerMockito.doNothing().when(Class1.class);
    Class1.doSomething();