有没有办法测试下面的类,嘲笑私有方法getMessage()
?
我已经尝试过jUnit + Mockito + PowerMock,但我找不到方法(不修改源代码或进行反射更改)。
知道吗?
public final class One {
public static String met1() {
return getMessage();
}
private static String getMessage() {
return "ciao";
}
private One() {
// Empty
}
}
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() );
}
}