In order to do the unit test for my child class, I tried to mock the super's method which is called inside the child's method.
But it seems impossible with Mockito.
I searched somewhere and it it said that jMockit can do what I want.
https://stackoverflow.com/questions/14125774/powermock-mocking-a-super-method-invocation
But some functions of JMockit were deprecated. So, I rewrote it.
This post maybe useful to who wanna use jMockit to mock super's method.
import org.junit.*;
import mockit.*;
abstract class BaseService { // jMockit can mock the super class no matter it is abstract or not
public int save() {
System.out.println("base service save executing...");
return 2;
}
public abstract void blabla();
}
class ChildService extends BaseService {
public int save() {
System.out.println("child service save executing...");
int y = super.save();
return 1 + y;
}
@Override
public void blabla() {
// TODO
}
}
// Below is the test part
class MockBase extends MockUp<BaseService>{
@Mock
public int save() {
System.out.println("mocked base");
return 9;
}
}
public class TestSuperCall {
@Test
public void testSave() throws Exception {
MockBase mockBase = new MockBase();
ChildService childService = new ChildService();
Assert.assertEquals(9 + 1, childService.save());
new Verifications() {{ mockBase.save(); }};
}
}
https://javadoc.io/doc/org.jmockit/jmockit/latest/index.html
For example, in this sample i downloaded jmockit-1.49.jar and put here.
Right click on the file containning your jMockit test code > Run As > JUnit Test