使用 mockito doThrow 测试 catch 块会立即执行
Posted
技术标签:
【中文标题】使用 mockito doThrow 测试 catch 块会立即执行【英文标题】:Testing catch block with mockito doThrow is executed immediately 【发布时间】: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);
【问题讨论】:
【参考方案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);
【讨论】:
以上是关于使用 mockito doThrow 测试 catch 块会立即执行的主要内容,如果未能解决你的问题,请参考以下文章