Mockito thenReturn返回相同的实例 [英] Mockito thenReturn returns same instance

查看:733
本文介绍了Mockito thenReturn返回相同的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Mockito中有这个:

I have this in Mockito:

when(mockedMergeContext.createNewEntityOfType(IService.class)).thenReturn(new ServiceMock());

createNewEntityOfType 方法应该总是返回一个新的 ServiceMock 实例但它返回两次相同的引用。

The createNewEntityOfType method should always return a new ServiceMock instance but it returns twice the same reference.

为什么 thenReturn 方法不会返回新的 ServiceMock

Why the thenReturn method doesn't return new ServiceMock?

推荐答案

thenReturn 方法将始终返回传递给它的内容。在调用 thenReturn 之前,正在执行代码 new Servicemock()。然后将创建的 ServiceMock 传递给 thenReturn 。因此 thenReturn 的绝对实例 ServiceMock 不是创建机制。

The thenReturn method will always return what is passed to it. The code new Servicemock() is being executed prior to the call to thenReturn. The created ServiceMock is then being passed to thenReturn. Therefore thenReturn has a absolute instance of ServiceMock not a creation mechanism.

如果您需要提供新实例,请使用 thenAnswer

If you need to provide an new instance, use thenAnswer

when(mockedMergeContext.createNewEntityOfType(IService.class))
  .thenAnswer(new Answer<IService>() {
     public IService answer(InvocationOnMock invocation) {
        return new ServiceMock();
     }
   });

这篇关于Mockito thenReturn返回相同的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆