How do I mock a method of a super class by Mockito?

Viewed 10930

I need to mock a call to the findById method of the GenericService.

I've this:

public class UserServiceImpl extends GenericServiceImpl<User Integer> implements UserService, Serializable {

.... 
// This call i want mock
user = findById(user.getId());
.....
// For example this one calls mockeo well. Why is not it a call to the generic service?
book = bookService.findById(id);

The problem is in the first mock since it is a call to a generic service.

The second mock works fine as well

when(bookService.findById(anyInt())).thenReturn(mockedBook);
3 Answers

Here is one example I found that resolved same issue in my case-

public class BaseController {

     public void method() {
          validate(); // I don't want to run this!
     }
}
public class JDrivenController extends BaseController {
    public void method(){
        super.method()
        load(); // I only want to test this!
    }
}

@Test
public void testSave() {
    JDrivenController spy = Mockito.spy(new JDrivenController());

    // Prevent/stub logic in super.method()
    Mockito.doNothing().when((BaseController)spy).validate();

    // When
    spy.method();

    // Then
    verify(spy).load();
}
Related