Mockito thenReturn returns same instance(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
方法将始终返回传递给它的内容.new Servicemock()
代码在调用 thenReturn
之前被执行.然后将创建的 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 返回相同的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mockito thenReturn 返回相同的实例


基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01