JUnit如何模拟超类

时间:2015-05-22 07:55:58

标签: junit

class A {

     int a;
     int b;

 }



class B extends A {

     public int add(){
         return a+b;
     }
 }

我想在子类B中测试方法add但是如何从超类A中模拟属性a,b。

1 个答案:

答案 0 :(得分:0)

我建议您对这些字段使用getterssetters

无论如何,显示您设置的代码并通过反射获取值。

以下是代码的反射部分:

  public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
  {
    B bObj = new B();
    Field aField = A.class.getDeclaredField("a");
    Field bField = A.class.getDeclaredField("b");
    aField.set(bObj, 5);
    bField.set(bObj, 10);

    // alternatively, if you had getters, you can see the values using them
    System.out.println(aField.getInt(bObj));
    System.out.println(bField.getInt(bObj));
  }

这将分别打印510