title: Mocking, not suppressing, a java super class constructor (with PowerMockito)
body: <p>I'm looking for a way to mock or otherwise stub the functionality of a parent class in a unit test for its childs constructor.  The Parent class itself is poorly designed, but untouchable due to contractual agreement.  We're using PowerMockito already, but PowerMock(EasyMock) is also on the list of approved libraries.  Here's the simplified code, along with my best attempt thus far at getting the unit test working:</p>
  
  <pre><code>/**
   * The class Parent is locked
   */
  public class Parent {
  
      private final Integer x;
      private final Integer y;
  
      public Parent(Integer x) {
          this.x = x;
          this.y = loadY();
      }
  
      private int loadY() {
          // Actual code loads a bunch of stuff from DB
          throw new RuntimeException();
      }
  
      protected Integer getSum() {
          return x+y;
      }
  }
  
  /**
   * This code is not locked, but Child MUST extend Parent and foo MUST be final.
   */
  public class Child extends Parent{
  
      private final Integer foo;
  
      public Child(int x) {
          super(x);
          foo = getSum();
      }
  
      public Integer getFoo() {
          return foo;
      }
  }
  
  @RunWith(PowerMockRunner.class)
  @PrepareForTest({Child.class, Parent.class})
  public class ChildTest {
  
      @Mock
      private Parent par;
  
      @Test
      public void testGetFoo() throws Exception {
  
          MemberModifier.suppress(MemberMatcher.constructor(Parent.class, Integer.class));
          PowerMockito.whenNew(MemberMatcher.constructor(Parent.class)).withNoArguments().thenReturn(par);
          Mockito.when(par.loadY()).thenReturn(new Integer(3));
          Mockito.when(par.getSum()).thenReturn(7);
  
          Child child = new Child(4);
  
          Assert.assertEquals(new Integer(7), child.getFoo());
      }
  }
  </code></pre>
  
  <p>I am able and willing to edit the class Child so long as it continues to extend Parent and foo is final, but I am unable to edit Parent in any way.  It would be more ideal to mock the call to getSum() as that would allow the verification of that call (not relevant here, but it could be in other scenarios). Still, mocking loadY() or setting the state of child.y seems acceptable, but setting child.foo does not seem correct.  I've spent a large chunk of the day bouncing back and forth between websites and eclipse trying to figure this out, but so far every run results in the expectable RTE or NPE.  Any Ideas?</p>