Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito How to mock only the call of a method of the superclass

Tags:

java

mockito

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?

like image 548
mada Avatar asked Aug 12 '10 12:08

mada


1 Answers

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();     } 
like image 53
jgonian Avatar answered Sep 27 '22 21:09

jgonian