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

Testing catch block with mockito doThrow is executed immediately

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

时抛出它

有什么问题吗?

@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);
}

我处理问题的方式完全错误。我按如下方式更改了代码,现在一切正常。

@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);
}