问题
直接invoke抽象类的mock对象会空指针异常。
抽象类
1 2 3 4 5 6 7 8
| public abstract class Base {
protected abstract String getName();
private String getHi(String v) { return "Hi " + v; } }
|
解决方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class Child extends Base { protected String getName() { return "Hello World"; } }
public class test() { @Test public void testMethod() { Child child = new Child(); try { Method method = Base.class.getDeclaredMethod("getHi", String.class); method.setAccessible(true); String output = (String) method.invoke(child, "Tuk"); System.out.println(output); } catch (Exception e) { e.printStackTrace(); } } }
|