Advertisement
obernardovieira

Mock a method on extended class without super()

Jun 1st, 2017
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.88 KB | None | 0 0
  1. /* special thanks to
  2.  * https://stackoverflow.com/questions/3467801/mockito-how-to-mock-only-the-call-of-a-method-of-the-superclass
  3.  * I did a few editions
  4.  *
  5.  * The method validate()in BaseService is never called during tests
  6.  */
  7.  
  8.  
  9. class BaseService {
  10.  
  11.     public void validate() {
  12.         throw new IllegalArgumentException(" I must not be called");
  13.     }
  14.  
  15.     public void save() {
  16.         // Save method of super will still be called.
  17.         validate();
  18.     }
  19. }
  20.  
  21. class ChildService extends BaseService {
  22.  
  23.     public void load() {
  24.     }
  25.  
  26.     public void save() {
  27.         load();
  28.     }
  29. }
  30.  
  31. @RunWith(MockitoJUnitRunner.class)
  32. public class TrainMlpScheduleSoftSensorService0Test {
  33.  
  34.     @Test
  35.     public void testSave() {
  36.         ChildService spy = Mockito.spy(new ChildService());
  37.  
  38.         // Prevent/stub logic in super.save()
  39.         Mockito.doNothing().when((BaseService) spy).validate();
  40.  
  41.         // When
  42.         spy.validate();
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement