简体   繁体   English

在最终(实用程序)类中模拟私有静态方法

[英]Mocking private static method in a final (utility) class

Is there a way to test the following class, mocking the private method getMessage() ? 有没有一种方法可以模拟私有方法getMessage()来测试以下类?

I've tried with jUnit + Mockito + PowerMock but I could not find a way (without modifying source code or doing reflection changes). 我已经尝试过使用jUnit + Mockito + PowerMock,但是找不到方法(无需修改源代码或进行反射更改)。

Any idea ? 任何想法 ?

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

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: PowerMockito将让您模拟该类的所有静态方法,但是您需要确保您的met1方法仍然调用真实方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM