我可以用Mockito/Powermock模拟一个超类的构造函数吗?

Jef*_*rod 7 java inheritance mockito powermock superclass

是否可以使用Mockito和可选的Powermock来模拟超类S,以便对超类的任何调用S(包括对S()构造函数的调用)进行模拟?因此,使用下面的例子,如果我更换SMockS使用的Mockito,将调用super()使用在构造函数MockS

class S {
   S() {
      // Format user's hard drive, call 911, and initiate self-destruct
   }
}

class T extends S {
   T() {
      super();
   }
}

class Test {
   @Mock private S mockS;
   new T(); // T's call to super() should call the mock, not the destructive S.
}
Run Code Online (Sandbox Code Playgroud)

我已经看到了关于模拟单个方法S或仅super()模拟调用的问题,并且认为这是不受支持的,但我不清楚是否可以模拟整个超类.

以我目前的测试中,当我试图嘲弄S,T的号召,super()要求真正落实,而不是模仿.

Jef*_*rod 5

为了解决这个明显的限制,我重构了我的代码,用 delegate 替换继承,并且我认为无论如何我都得到了更好的设计,因为继承并不是真正必要的。

新代码如下所示。请注意,问题的代码已简化,因此真正的类具有更多功能。

class S {
   S() {
      // Format user's hard drive, call 911, and initiate self-destruct
   }
}

class T {
   T(S s) {} // Now T "has an S" instead of "is an S"
}

class Test {
   @Mock private S mockS;
   new T(s); // T's call to super() should call the mock, not the destructive S.
}
Run Code Online (Sandbox Code Playgroud)

对于那些感兴趣的人来说,使用 Guice 和 Android,测试看起来更像这样:

class T {
   T(Activity activity, S s) {}
}

class Test {
  @Mock Activity activity;
  @Mock S mockS;
  injector = Guice.createInjector(new AbstractModule() {
     @Override protected void configure() {
        bind(Activity.class).toInstance(activity);
        bind(S.class).toInstance(mockS);
     }}
  );
  T t = injector.getInstance(T.class);
}
Run Code Online (Sandbox Code Playgroud)