Gualtiero Testa
Gualtiero Testa

Reputation: 244

Mocking private static method in a final (utility) class

Is there a way to test the following class, mocking the private method getMessage() ?

I've tried with jUnit + Mockito + PowerMock but I could not find a way (without modifying source code or doing reflection changes).

Any idea ?

public final class One {
    public static String met1() {
        return getMessage();
    }
    private static String getMessage() {
        return "ciao";
    }
    private One() {
        // Empty
    }
}

Upvotes: 1

Views: 2249

Answers (1)

Nick Wilson
Nick Wilson

Reputation: 4989

PowerMockito will let you mock all of the static methods of the class, but you need to make sure your met1 method still calls the real method:

@RunWith( PowerMockRunner.class )
@PrepareForTest( One.class )
public class OneTest
{
  @Test
  public void testOne()
  {
    PowerMockito.mockStatic( One.class );
    try
    {
      PowerMockito.when( One.met1() ).thenCallRealMethod();
      Method getMessage = PowerMockito.method( One.class, "getMessage" );
      PowerMockito.when( getMessage.invoke( null ) ).thenReturn( "test" );
    }
    catch ( Exception e )
    {
      e.printStackTrace();
    }
    assertEquals( "test", One.met1() );
  }
}

Upvotes: 1

Related Questions