Powermock static final method in final class

Viewed 36061

The Test case I am writing for:

public class AClassUnderTest {

    // This test class has a method call
    public Long methodUnderTest() {

         // Uses the FinalUtilityClass which contains static final method
         FinalUtilityClass.myStaticFinalMethod(<3-parameters-here>);

         // I want to mock above call so that test case for my "methodUnderTest" passes
    }
}

I have one final class.

public final class FinalUtilityClass {

   /**
    * Method has 3 parameters
    */
   public static final MyBean myStaticFinalMethod(<3-parameters-here>) {

   }
}

I have already added below code in my test class:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ FinalUtilityClass.class })

I want to write test case for mocking it. I want to mock the call of myStaticFinalMethod() so that I can get the expected MyBean instatnce which I can use in further code to pass my test case.

The <3-parameters-here> are Calendar, String, String.

I tried doing:

1)

PowerMockito.mock(FinalUtilityClass.class)
PowerMockito.when(FinalUtilityClass.myStaticFinalMethod(<3-parameters-here>).thenReturn(new MyBean());

2)

PowerMockito.mockStatic(FinalUtilityClass.class)
PowerMockito.when(FinalUtilityClass.myStaticFinalMethod(<3-parameters-here>).thenReturn(new MyBean());

3)

PowerMockito.spy(FinalUtilityClass.class)
PowerMockito.when(FinalUtilityClass.myStaticFinalMethod(<3-parameters-here>).thenReturn(new MyBean());

But nothing worked for me. Please suggest what is correct way for mocking static final method in final class.

2 Answers

I faced a similar problem, and it cost me a lot of time.

I solved it, based on this Mock system class with PowerMock documentation, when I realized that the @PrepareForTest({ SomeClassToBePreparedForTesting.class }) must receive the class that calls the static methods defined in the final class, so the preparation for the test, in your case, must receive the AClassUnderTest.class.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ AClassUnderTest.class })

The correct way to mock the final class with the target static method is to use the PowerMock.mockStatic(FinalClassThatDefinesStaticMethod.class), in your case the FinalUtilityClass.class.

PowerMockito.mockStatic(FinalUtilityClass.class)
PowerMockito.when(FinalUtilityClass.method(params)).thenReturn(return);

In addition, if you have some issue like: 'It's not possible to mock final methods', you can create the file org/powermock/extensions/configuration.properties and set this config mockito.mock-maker-class=mock-maker-inline like the PowerMockito documentation presents.

Related