首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >立即执行使用mockito doThrow的测试catch块

立即执行使用mockito doThrow的测试catch块
EN

Stack Overflow用户
提问于 2021-12-22 14:30:29
回答 1查看 187关注 0票数 0

我想用mockito测试我的方法的catch块。如下面的示例所示,我在希望异常发生的地方使用Mockito.doThrow。然后调用包含此调用的方法。但是这行永远不会执行,因为在doThrow行上,异常会立即抛出。我期望在调用下一行(spyDataGridService.createMap(mapName))时抛出它。

这是怎么回事?

代码语言:javascript
复制
@Override
public String createMap(String mapName) {
    String result;
    try {
        RemoteCache remoteCache = remoteCacheManager.getCache(mapName);
        if(remoteCache != null) {
            removeMap(mapName);
        }

        remoteCacheManager.administration().createCache(mapName, new XMLStringConfiguration(String.format("<distributed-cache name=\"%s\" mode=\"SYNC\" statistics=\"true\"><encoding media-type=\"text/plain\"/><memory><object size=\"2000000\"/></memory><expiration lifespan=\"3600000\"/><state-transfer timeout=\"3600000\" /></distributed-cache>", mapName)));

        dataGridBeanConfiguration.getConfigurationBuilder().build();

        result = String.format("Map: '%s', the map has been created.", mapName);
        logger.info(result);
    } catch (Exception e) {
        result = String.format("Map: '%s', create map error: %s", mapName, e.getMessage());
        logger.error(result);
    }
    return result;
}

@Test(expected = Exception.class)
public void testCreateMapException() {
    RemoteCacheManager mockRemoteCacheManager = Mockito.mock(RemoteCacheManager.class);
    DataGridBeanConfiguration mockDataGridBeanConfiguration = Mockito.mock(DataGridBeanConfiguration.class);
    DataGridService spyDataGridService = Mockito.spy(new 
    DataGridServiceImpl(mockRemoteCacheManager, mockDataGridBeanConfiguration));
        
    Mockito.doThrow(Exception.class).when(mockRemoteCacheManager).getCache(Mockito.anyString());

    spyDataGridService.createMap(mapName);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-22 19:52:24

我完全错误地处理了这个问题。我修改了代码,如下所示,现在一切都如我所期望的那样工作。

代码语言:javascript
复制
@Test
public void testCreateMapException() {
    RemoteCacheManager mockRemoteCacheManager = Mockito.mock(RemoteCacheManager.class);
    DataGridBeanConfiguration mockDataGridBeanConfiguration = Mockito.mock(DataGridBeanConfiguration.class);
    DataGridService spyDataGridService = Mockito.spy(new DataGridServiceImpl(mockRemoteCacheManager, mockDataGridBeanConfiguration));

    String result = spyDataGridService.createMap(mapName);

    String expectedMessage = String.format("Map: '%s', create map error: null", mapName);

    Assert.assertEquals(expectedMessage, result);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70450626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档