How to use Mockito or PowerMock to mock a protected method implemented by a subclass, but inherited from an abstract superclass?
In other words, I want to test the doSomething method by making fun of "doSomethingElse".
Abstract superclass
public abstract class TypeA { public void doSomething() {
Subclass implementation
public class TypeB extends TypeA { @Override protected String doSomethingElse() { return "this method needs to be mocked"; } }
Decision
The answers given here are correct and will work if the participating classes are in the same package.
But if different packages are involved, one of them is for the PowerMock user. The following example worked for me. Of course, there may be other ways to do this, it works.
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 {
Note. Tests are performed using Java 5, jUnit 4.11, Mockito 1.9.0, and PowerMock 1.4.12.
source share