有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 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;
    }
}

是什么导致调用真正的实现,如何防止调用


共 (1) 个答案

  1. # 1 楼答案

    Mockito代码无法访问您正在模拟的方法

    因为测试代码和测试中的代码在同一个包中,编译器允许您以这种方式设置模拟,但是在运行时,Mockito库必须尝试访问moveAttachment,但它在您的情况下不起作用。这似乎是Mockito中的bugknown limitation,因为它应该支持这种情况(事实上,在大多数情况下确实支持这种情况)

    最简单的方法是使moveAttachment成为公共方法。如果这不是一个选项,那么首先要问你是否想嘲笑它。如果调用了实方法,会发生什么

    最后一个选项是使用PowerMockmoveAttachment方法视为私有方法,并以这种方式对其进行模拟