【问题标题】:How to Change private Abstract Parent Fields for Legacy Unit Test如何更改旧版单元测试的私有抽象父字段
【发布时间】:2014-07-29 20:27:41
【问题描述】:

如果我有:

 public abstract class A {
      private Object target; // <- **IMPORTANT**

      protected Blah blah    // ... Not directly relevant to the question, 
      protected Blah blah2   //     they are just a potential reason to extend 
                             //     test class ...?

      public int func (){
          int hello = Integer.parseInt(target.Fields.want2Change);
          return hello;
      }     
  }

我想测试 A 类。 因为它是抽象的,所以我用 ATest 类来扩展它。 还有其他领域,但它们受到保护,这是合理的。

我的问题来自儿童班,我如何访问 parenttarget 这样的私人字段。

我混合使用了模拟 (Mockito) 和反射。

我也尝试过只使用反射而不是扩展类。

【问题讨论】:

标签: java unit-testing reflection parent-child legacy


【解决方案1】:

这并不能直接回答您的问题,但是否可以通过某种方式执行父类的公共 api 来测试私有字段状态?

如果你能做到这一点,那么就不需要反思,这可能更易于长期维护。

如果不是,那么您必须扩展类并使用 r 选举来获取私有属性的句柄。

看到这个帖子:

Access to private inherited fields via reflection in Java

【讨论】:

  • 是的,这段代码实际上没有 getter 或 setter。 ://
猜你喜欢
  • 2016-10-25
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
相关资源
最近更新 更多