是否有 RETURNS_DEEP_STUBS 的替代方法来使用 Mockito 模拟链式方法?

Is there an alternative to RETURNS_DEEP_STUBS for mocking chained methods with Mockito?

我有一个允许方法链接的数据库服务 save() 方法:

@Service
public class Service {
...
    public Service save(...) {
        ...     
        return this;
    }

这很好用:

service.save(this).save(that).save(other);

当我用 Mockito 模拟它时,尽管它会中断,除非我使用

Service serviceMock = mock(Service.class, RETURNS_DEEP_STUBS); 

IIUC 但是,使用 RETURNS_DEEP_STUBS 被认为是不好的。有没有更好的方法通过方法调用链来模拟 class?

save 的模式与 Builder 模式非常相似,这使得问题类似于 SO 其他地方的“How to mock a builder with mockito”。

根据 Mockito 2.0 中的 David Wallace's answer there, you can write an Answer that detects whether the mock is an instance of the return type of the method, and return the mock in only that case. This functionality was also built into the Mockito library as RETURNS_SELF。与任何答案一样,您可以在使用 thenAnswer 的任何特定方法调用上使用它或将其用作 mock 的第二个参数以使其成为默认答案,但请记住 Mockito 文档警告该方法具有慷慨return 类型(例如 Object)将 return 模拟,无论是否有意。