How do I mock a static method in the final class?

I have some code that has a static method inside the final class. I tried to mock this method. I've tried several things.

public final Class Class1{

 public static void doSomething(){
  } 
}

      

How can I mock doSomething ()? I 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)

      

+3


source to share


2 answers


The most commonly used testing framework is JUnit 4. Therefore, if you are using it, you need to annotate the test class:

@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();

      

0


source


I am using PowerMock. This allows you to do what Mokito cannot. https://github.com/powermock/powermock/wiki



@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticClass.class)
public class StaticTest {

@Before
public void setUp() {
    PowerMockito.mockStatic(Bukkit.class);

    //When a static method with no arguments is called.
    when(StaticClass.callMethod1()).thenReturn(value);

    //When a static method with an argument is called.
    when(StaticClass.callMethod2(argument)).thenReturn(value2);

    //Use when you don't care what the argument is..   
    //use Mockito.anyInt(), Mockito.anyDouble(), etc.

    when(StaticClass.callMethod3(Mockito.anyString())).thenReturn(value3);
  }

@Test
public void VerifyStaticMethodsWork() {
    assertEquals(value, StaticClass.callMethod1());
    assertEquals(value2, StaticClass.callMethod2(argument));
    assertEquals(value3, StaticClass.callMethod3("Hello"));
}

}

      

0


source







All Articles