问题
Sometimes when I write unit tests I should to mock reference to superclass.
I have read this question: question
This answer answer with DI advice to refactor code. But I cannot it
this answer another answer is not suitable if superclass method is enough big. In my case I have very big code. Yes I know that it is brokes SOLID OOD principes but I just should to write test. I have not enough time for refactor.
said question was asked 4 years ago!
Does currently Mockito or Powermock can resolve this issue ?
update
code example:
class BaseService {
public void save() {
// a lot of code here! I cannot change this code.
}
}
public Childservice extends BaseService {
public void save(){
//logic for testing
super.save();
//logic for testing
}
}
update 2
public class Parent {
public int save() {
return 99;
}
}
public class Child extends Parent {
public int save() {
int i = super.save();
return i*2;
}
}
and test:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Parent.class)
public class ParentTest {
@Test
public void testSave() {
PowerMockito.suppress(PowerMockito.methodsDeclaredIn(Parent.class));
System.out.println(new Child().save());
}
}
output: 198
回答1:
With Powermock you can replace or suppress methods, so it is possible to change the action done by BaseService.save()
. You can also make methods to do nothing with suppressing. You can even suppress static initializer blocks.
Please read this blog entry of the Powermock authors. See chapter "Replacing".
UPDATE:
Suppress seems to work for me, but replace not. See the picture below:
回答2:
This is impossible; the whole point of a superclass is that it encapsulates upstream state and functionality, and the class hierarchy is hard-coded in your subclass based on the extends
relationship.
来源:https://stackoverflow.com/questions/23865555/how-to-mock-super-reference-on-super-class