簡體   English   中英

在模仿中檢索模仿對象名稱

[英]Retrieving mocked object name in mockito in

所以我正在使用doAnswer()API模擬Node類的方法setProperty(String,String)

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方法的參數。 但是我無法檢索嘲笑對象名(在這種情況下為“ attachmentsJcr”)。

模擬對象沒有“名稱”。 模擬對象存在的唯一原因是允許您控制被測代碼與注入模擬對象進行交互時“看到”的行為。

換一種說法:

Node attachmentsJcr = mock(Node.class);   

創建一個“真正”的Node對象。 是的, attachmentsJcr是對Node對象的引用; 但是此對象是由模擬框架“神奇地”創建的。 它沒有Node對象的“真實”屬性。 它不僅可以讓你調用一個Node對象將提供方法

從這個意義上說:如果您的Node類具有類似getName()的方法,那么返回的名稱就是您配置為模擬以在調用getName()時返回的名稱。

並且要確保:AnswerImpl不是“生產代碼”,對嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM