在 mockito 中检索模拟对象名称

Retrieving mocked object name in mockito in

所以我正在使用 doAnswer() API 模拟节点的方法 setProperty(String,String) class

Node attachmentsJcr = mock(Node.class);        
doAnswer(AnswerImpl.getAnswerImpl()).when(attachmentsJcr).setProperty(anyString(),anyString());

AnswerImpl实现如下-

public class AnswerImpl implements Answer{

    private static AnswerImpl instance;

    private AnswerImpl(){
    }

    public  static AnswerImpl getAnswerImpl(){
        if(instance == null){
            instance = new AnswerImpl();
            return instance;
        }
        else
            return instance;
    }

    @Override
    public Object answer(InvocationOnMock invocationOnMock) throws Throwable {

        final String key = (String)(invocationOnMock.getArguments())[0];
        final String value = (String)(invocationOnMock.getArguments())[1];
        final String mockedObjectName = ? 
        results.put(key,value); // results here is a hashhmap
        return mockedObjectName;
    }
}

我能够检索传递给 setProperty 方法的参数。 但我无法检索 mockedObjectName("attachmentsJcr" 在这种情况下)。

模拟对象没有 "names"。模拟对象存在的唯一原因是允许您 控制 被测代码在与注入其中的模拟对象交互时 "sees" 的行为。

换句话说:

Node attachmentsJcr = mock(Node.class);   

不会 创建 "real" 节点对象。是的,attachmentsJcr 是对 Node 对象的引用;但是这个对象是由模拟框架 "magically" 创建的。它没有 Node 对象的 "real" 属性。它只允许您调用 Node 对象提供的 方法

从这个意义上说:如果您的节点 class 具有类似 getName() 的方法...那么 returned 名称就是您配置为模拟的名称 return 在调用 getName() 时。

而且可以肯定的是:AnswerImpl 不是 "production code",是吗?