【发布时间】:2014-07-21 23:50:58
【问题描述】:
我正在尝试使用 Mockito 1.8.5 对方法进行存根,但这样做会调用引发异常的真实方法实现(使用 "" 作为参数值)。
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;
}
}
是什么导致真正的实现被调用,我该如何防止它?
【问题讨论】:
-
你能添加实际执行测试的代码吗?
-
是
FileAttachmentContainer还是方法moveAttachment()最终? Mockito 无法模拟最终方法。 -
真的用 anyString() 的值调用 moveAttachment 吗?
-
你的测试类和
FileAttachmentContainer在同一个包里吗?如果没有,它将无法访问moveAttachment。 -
这看起来可能是一个注入问题 - 就像模拟设置正确,但模拟并不是真正在测试中使用的对象。如果您能向我们展示测试的代码和实际正在测试的代码,那将很有帮助。