简体   繁体   English

在模仿中检索模仿对象名称

[英]Retrieving mocked object name in mockito in

So I am using doAnswer() API to mock a method setProperty(String,String) of the Node class 所以我正在使用doAnswer()API模拟Node类的方法setProperty(String,String)

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

AnswerImpl is implemented below- 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;
    }
}

I was able to retrieve the arguments that was passed to the setProperty method. 我能够检索传递给setProperty方法的参数。 But I am unable to retrieve the mockedObjectName("attachmentsJcr" in this case). 但是我无法检索嘲笑对象名(在这种情况下为“ attachmentsJcr”)。

Mocked objects do not have "names". 模拟对象没有“名称”。 The only reason for a mock object to exist is to allow you to control the behavior that your code under test "sees" when interacting with mock objects injected into it. 模拟对象存在的唯一原因是允许您控制被测代码与注入模拟对象进行交互时“看到”的行为。

In other words: 换一种说法:

Node attachmentsJcr = mock(Node.class);   

does not create a "real" Node object. 创建一个“真正”的Node对象。 Yes, attachmentsJcr is a reference to a Node object; 是的, attachmentsJcr是对Node对象的引用; but this object was "magically" created by the mocking framework. 但是此对象是由模拟框架“神奇地”创建的。 It doesn't have the "real" properties of a Node object. 它没有Node对象的“真实”属性。 It only allows you to call the methods that a Node object would offer. 它不仅可以让你调用一个Node对象将提供方法

In that sense: if your Node class has a method like getName() ... then the returned name is simply that which you configured to mock to return upon calls to getName(). 从这个意义上说:如果您的Node类具有类似getName()的方法,那么返回的名称就是您配置为模拟以在调用getName()时返回的名称。

And just to be sure: AnswerImpl is not "production code", is it? 并且要确保:AnswerImpl不是“生产代码”,对吗?

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

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