如何模拟内部调用方法?

时间:2019-01-18 14:18:29

标签: java mockito

下面是我尝试为其编写文本大小写并添加我所做的但得到空指针exp的代码

public boolean doVersionLimitCheck(Long mneId) throws DMMException {
    CALogUtil.getInstance().logMethodEntry("doVersionLimitCheck",
            ConfigArchiveManagerImpl.class.getName());
    boolean status = false;
    status = validateArchivedVersions(mneId);
    CALogUtil.getInstance().logDebug("Version Roll over status::" + status);
    CALogUtil.getInstance().logMethodExit("doVersionLimitCheck",
            ConfigArchiveManagerImpl.class.getName());
    return status;
}

为此,我确实喜欢以下内容。

@Test
public void testDoVersionLimitCheck() {

    Long mneId=Long.valueOf("123");
    ConfigArchiveManagerImpl impl = new ConfigArchiveManagerImpl();
    try {
        Mockito.doReturn(true).when(Mockito.mock(ConfigArchiveManagerImpl.class)).validateArchivedVersions(Mockito.anyLong());
    } catch (DMMException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        impl.doVersionLimitCheck(mneId);
    } catch (DMMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

您需要监视SUT才能测试一种方法并模拟另一种方法:

@Test
public void testDoVersionLimitCheck() {

    Long mneId=Long.valueOf("123");
    ConfigArchiveManagerImpl impl = Mockito.spy(new ConfigArchiveManagerImpl());
    try {
        Mockito.doReturn(true).when(impl ).validateArchivedVersions(Mockito.anyLong());
    } catch (DMMException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }