package testng;
public class PrivateMethod {
private String username;
private void init() {
System.out.println("init...");
this.username = "init username";
}
}
package testng;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PrivateMethodTest {
@Test
public void verifyInit() throws Exception {
PrivateMethod pm = new PrivateMethod();
//验证username域是否为空
Field f = pm.getClass().getDeclaredField("username");
f.setAccessible(true);
Object valueBefore = f.get(pm);
Assert.assertNull(valueBefore);
//调用init方法
Method method = pm.getClass().getDeclaredMethod("init", null);
method.setAccessible(true);
method.invoke(pm, null);
//验证username域是否为空
Object valueAfter = f.get(pm);
Assert.assertNotNull(valueAfter);
}
}