Mockito mock 在尝试存根包保护方法时调用实际方法实现
我试图使用Mockito 1.8.5来存根一个方法,但这样做会调用真正的方法实现(将“”作为parm值),这会引发异常。
package background.internal; //located in trunk/tests/java/background/internal
public class MoveStepTest {
@Test
public void testMoveUpdate() {
final String returnValue = "value";
final FileAttachmentContainer file = mock(FileAttachmentContainer.class);
doReturn(returnValue).when(file).moveAttachment(anyString(), anyString(), anyString());
//this also fails
//when(file.moveAttachment(anyString(), anyString(), anyString())).thenReturn(returnValue);
final AttachmentMoveStep move = new AttachmentMoveStep(file);
final Action moveResult = move.advance(1, mock(Context.class));
assertEquals(Action.done, moveResult);
}
}
我试图嘲笑的方法看起来像这样。没有最终的方法或类。
package background.internal; //located in trunk/src/background/internal
public class FileAttachmentContainer {
String moveAttachment(final String arg1, final String arg2, final String arg3)
throws CustomException {
...
}
String getPersistedValue(final Context context) {
...
}
}
我通过模拟的类看起来像这样:
package background.internal; //located in trunk/src/background/internal
public class AttachmentMoveStep {
private final FileAttachmentContainer file;
public AttachmentMoveStep(final FileAttachmentContainer file) {
this.file = file;
}
public Action advance(final double acceleration, final Context context) {
try {
final String attachmentValue = this.file.getPersistedValue(context);
final String entryId = this.file.moveAttachment(attachmentValue, "attachment", context.getUserName());
//do some other stuff with entryId
} catch (CustomException e) {
e.log(context);
}
return Action.done;
}
}
是什么原因导致实际实现被调用,我该如何防止它?