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