有没有办法测试下面的类,模拟私有方法getMessage()
?
我尝试过使用jUnit + Mockito + PowerMock,但我找不到办法(不修改源代码或进行反射更改)。
有什么想法吗?
public final class One {
public static String met1() {
return getMessage();
}
private static String getMessage() {
return "ciao";
}
private One() {
// Empty
}
}
答案 0 :(得分:1)
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() );
}
}