Java项目开发过程中,有时需要测试类的私有方法,而私有方法不能直接调用,但可以利用反射机制来进行调用,下面是一个例子:
@Test
public void testGetElectionTimeout() throws Exception {
int confTimeout = conf1.getInt("raft.election.timeout");
Method m = node1.getClass().getDeclaredMethod("getElectionTimeout", new Class[] {});
m.setAccessible(true);
for(int i = 0; i < 100; i++) {
Object result = m.invoke(node1, null);
int resultInt = ((Integer)result).intValue();
System.out.println(result);
assertTrue(resultInt >= confTimeout);
assertTrue(resultInt <= confTimeout*2);
}
}
本文介绍如何使用Java反射机制测试类中的私有方法,并通过一个具体示例展示如何调用私有方法并验证其返回结果。
1559

被折叠的 条评论
为什么被折叠?



