【问题标题】:Testing catch block with mockito doThrow is executed immediately使用 mockito doThrow 测试 catch 块会立即执行
【发布时间】:2022-01-23 18:30:00
【问题描述】:

我想使用 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);
}

【问题讨论】:

    标签: testing exception mockito try-catch block


    【解决方案1】:

    我以完全错误的方式解决问题。我将代码更改如下,现在一切正常。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-17
      • 2021-08-16
      • 2023-03-06
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      相关资源
      最近更新 更多