Katarzynasrom / powermock

Automatically exported from code.google.com/p/powermock
0 stars 0 forks source link

Super keyword prevents mocking of method with a spy #467

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I am using Java 6, JUnit 4.11, Mockito 1.9.5 and PowerMock 1.5.

Problem statement:

Having two classes where one extends the other, say:

public class Parent {
   public void doSomething(String id) {
   }
}

public class Child extends Parent {
   public void doSomethingElse(String id) {
      //do stuff
      super.doSomething(id);
   }
}

The methods are different and do not override.  In my test of Child, I need to 
both mock a constructor and spy the Child class. For the spy, I need to do 
nothing when the method doSomething(...) is called.  My test class looks 
something like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Child.class)  //In order to mock a constructor
public class ChildTest {

    @InjectMocks
    private Child child;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
    }

    @After
    public void tearDown() throws Exception {
        validateMockitoUsage();
    }

    @Test
    public void testDoSomethingElse() {
        Child childSpy = PowerMocktio.spy(child);
        PowerMockito.doNothing().when(childSpy).doSomething(anyString());

        //Run the test:
        childSpy.doSomethingElse("id");
    }
}

My test fails as the doSomething(...) method in Parent is actually called. 
However, if I change the application code in Child and remove the super 
keyword, the spy mocks the method just fine and the test passes.  To be 
specific, I have to change Child to look like this:

public class Child extends Parent {
   public void doSomethingElse(String id) {
      //do stuff
      doSomething(id);
   }
}

Original issue reported on code.google.com by UndeadHi...@gmail.com on 15 Oct 2013 at 10:54