Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 365
user3453784 Avatar asked Nov 02 '14 15:11

user3453784


1 Answers

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();
like image 113
luboskrnac Avatar answered Oct 13 '22 05:10

luboskrnac