简体   繁体   English

在Mockito中调用真实方法,但拦截结果

[英]Calling real method in Mockito, but intercepting the result

Simplifying a bit, our system has two parts. 简化一下,我们的系统有两个部分。 "Our" part, which in turn uses an lower level part implemented by another team (in the same codebase). “我们的”部分,反过来使用由另一个团队(在相同的代码库中)实现的较低级别部分。 We have a fairly complicated functional test setup, where we wrap the entry points to the lower level in spy objects. 我们有一个相当复杂的功能测试设置,我们将入口点包装在间谍对象的较低层。 In positive tests we use the real implementation of that level, but we mock calls that should fail with some predefined error. 在积极的测试中,我们使用该级别的实际实现,但是我们模拟了应该因某些预定义错误而失败的调用。

Now I am trying to add support for more complicated scenarios, where I would like to add an artificial delay for the calls made to the underlying level (on a fake clock obviously). 现在我正在尝试添加对更复杂场景的支持,我想为基础级别的调用添加一个人工延迟(显然是假的时钟)。 To do this I would like to define a mock that would (1) Call the real implementation (2) Get the resulting Future object that is returned and combine it with a custom function that would inject the delay accordingly. 为此,我想定义一个模拟,它将(1)调用实际实现(2)获取返回的结果Future对象,并将其与自定义函数相结合,该函数将相应地注入延迟。 So Ideally I would like to have something like: 所以理想情况下我希望有类似的东西:

doAnswer(invocationOnMock -> 
    { 
      result = call real method on mySpy; 
      return Futures.combile(result, myFunction);
    }).when(mySpy).myMethod();

How can I achieve it? 我怎样才能实现它?

As for me the easiest way it's just to save the link to the read object when you initialize your Spy object: 至于我,最简单的方法就是在初始化Spy对象时保存读取对象的链接:

Foo realFoo = new Foo();
Foo spyFoo = Mockito.spy(realFoo);

Now you can stub it like this: 现在你可以像这样存根:

doAnswer(invocation -> realFoo.getSome() + "spyMethod").when(spyFoo).getSome();

One more way is to call invocation.callRealMethod() : 另一种方法是调用invocation.callRealMethod()

doAnswer(invocation -> invocation.callRealMethod() + "spyMethod").when(spyFoo).getSome();

But in this case you may need to cast the return value as long as invocation.callRealMethod() returns Object . 但在这种情况下,只要invocation.callRealMethod()返回Object您可能需要转换返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM