[英]is there any way in Mockito I set a rule to return a value when a property of a specific object type is called?
[英]Is there a way in Mockito to return the object if it was received?
有没有办法在 Mockito 中返回接收到的对象? 我想做这个模拟对象在数据库中的保存。 像这样的东西:
someClass someObj = ...;
when(dataProviderMock.insert(someObj))
.then(
when(dataProviderMock.read(someObj.getId()))
.thenReturn(someObj)
);
你所追求的是来自 Mockito 的ArgumentCaptor
查看其他问题
我不确定它的好处,但这会起作用:
// 将保存的对象保存在地图中
Map<Integer, Object> savedObjects = new HashMap<>();
// Saves the object in the map
when(dataProviderMock.insert(any(SomeClass.class))).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
SomeClass someObj = ((SomeClass)invocation.getArgument(0));
savedObjects.put(someObj.getId(), someObj);
return null;
}
});
// retrieves the object from the map or null if it was not previously saved
when(dataProviderMock.read(any(Integer.class))).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Integer id = ((Integer)invocation.getArgument(0));
return savedObjects.get(id);
}
});
如果我理解正确,您想在调用插入时返回一个对象。 如果您的插入函数具有 someObj 的返回类型。 您可以使用直接返回对象
when(dataProviderMock.insert(someObj)).thenReturn(someObj)
如果dataProviderMock.insert()
函数的返回类型为void
,则可以执行以下操作:
doNothing().doReturn(someObj).when(dataProviderMock).insert(someObj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.