I'm using Mockito in some tests.
I have the following classes:
class BaseService { public void save() {...} } public Childservice extends BaseService { public void save(){ //some code super.save(); } }
I want to mock only the second call (super.save
) of ChildService
. The first call must call the real method. Is there a way to do that?
If you really don't have a choice for refactoring you can mock/stub everything in the super method call e.g.
class BaseService { public void validate(){ fail(" I must not be called"); } public void save(){ //Save method of super will still be called. validate(); } } class ChildService extends BaseService{ public void load(){} public void save(){ super.save(); load(); } } @Test public void testSave() { ChildService classToTest = Mockito.spy(new ChildService()); // Prevent/stub logic in super.save() Mockito.doNothing().when((BaseService)classToTest).validate(); // When classToTest.save(); // Then verify(classToTest).load(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With