如何通过 Mockito 模拟超类的方法?

daf*_*nte 6 java junit mockito

我需要模拟对 GenericService 的 findById 方法的调用。

我有这个:

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);
Run Code Online (Sandbox Code Playgroud)

问题出在第一个模拟中,因为它是对通用服务的调用。

第二个模拟也很好用

when(bookService.findById(anyInt())).thenReturn(mockedBook);
Run Code Online (Sandbox Code Playgroud)

nik*_*nik 8

这是我发现在我的案例中解决了相同问题的一个例子 -

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();
}
Run Code Online (Sandbox Code Playgroud)


Anu*_*dda -3

您实际上是在尝试模拟超类实现,听起来是一个糟糕的设计。
如果无法重构,可以使用Powermock

尝试查看这篇文章:Mockito How to mock only the call of a method of the superclass

它可能会有所帮助