So I am using doAnswer() API to mock a method setProperty(String,String) of the Node class
Node attachmentsJcr = mock(Node.class);
doAnswer(AnswerImpl.getAnswerImpl()).when(attachmentsJcr).setProperty(anyString(),anyString());
AnswerImpl is implemented below-
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. But I am unable to retrieve the mockedObjectName("attachmentsJcr" in this case).
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. Yes, attachmentsJcr
is a reference to a Node object; but this object was "magically" created by the mocking framework. It doesn't have the "real" properties of a Node object. It only allows you to call the methods that a Node object would offer.
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().
And just to be sure: AnswerImpl is not "production code", is it?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.