我想用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);
}发布于 2021-12-22 19:52:24
我完全错误地处理了这个问题。我修改了代码,如下所示,现在一切都如我所期望的那样工作。
@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);
}https://stackoverflow.com/questions/70450626
复制相似问题