title: How to mock protected subclass method inherited from abstract class?
body: <p>How to use Mockito or PowerMock to mock a protected method that is realized by a subclass, but inherited from an abstract super class?</p>
  
  <p>In other words, I want to test "doSomething" method while mocking the "doSomethingElse".</p>
  
  <p><strong>Abstract super class</strong></p>
  
  <pre><code>public abstract class TypeA {
  
      public void doSomething() {     
  
          // Calls for subclass behavior
          doSomethingElse();      
      }
  
      protected abstract String doSomethingElse();
  
  }
  </code></pre>
  
  <p><strong>Subclass implementation</strong></p>
  
  <pre><code>public class TypeB extends TypeA {
  
      @Override
      protected String doSomethingElse() {
          return "this method needs to be mocked";
      }
  
  }
  </code></pre>
  
  <p><strong><em>Solution</em></strong></p>
  
  <p>Answers given here are correct and will work if classes involved are in the same package.</p>
  
  <p>But if <strong>different packages</strong> are involved one option is to user PowerMock. The following example worked for me. Of course there might be other ways of doing it, this is one that works.</p>
  
  <pre><code>import static org.junit.Assert.assertEquals;
  import org.junit.Test;
  import org.junit.runner.RunWith;
  import org.powermock.api.mockito.PowerMockito;
  import org.powermock.core.classloader.annotations.PrepareForTest;
  import org.powermock.modules.junit4.PowerMockRunner;
  
  @RunWith(PowerMockRunner.class)
  @PrepareForTest({ TypeB.class })
  public class TestAbstract {
  
      @Test
      public void test_UsingPowerMock() throws Exception {
          // Spy a subclass using PowerMock
          TypeB b = PowerMockito.spy(new TypeB());
          String expected = "some value for mock";
  
          // Mock a method by its name using PowerMock again
          PowerMockito.doReturn(expected).when(b, "doSomethingElse");
  
          // Calls the 
          String actual = b.doSomething();
          assertEquals(expected, actual);     
  
      }
  }
  </code></pre>
  
  <p>Note: <em>Tests done using Java 5, jUnit 4.11, Mockito 1.9.0 and PowerMock 1.4.12.</em> </p>