【发布时间】:2018-06-29 13:14:52
【问题描述】:
我正在尝试编写一个单元测试,它在我模拟的 RetryTemplate 上引发异常。当前测试对我的断言失败。
/**
* Test maybeSendNotification() IOException.
*/
@Test(expected = RuntimeException.class)
public void testMaybeSendNotificationIOException() throws IOException
{
Instance instance = new Instance();
instance.setState(new InstanceState().withName("DOWN"));
instance.setKeyName("prod");
EasyMock.expect(slackMessageSender.send(EasyMock.isA(HashMap.class))).andThrow(new RuntimeException());
EasyMock.replay(slackMessageSender);
assertFalse(instanceService.maybeSendNotification(instance));
EasyMock.verify(slackMessageSender);
}
slackMessageSender 和 retryTemplate 都是模拟。
这是正在测试的方法:
boolean maybeSendNotification(Instance newInstance)
{
Map<String, String> context = new HashMap<String, String>();
context.put("message", format("Instance with ID '%s' for load balancer '%s' status is DOWN.",
newInstance.getInstanceId(),
newInstance.getKeyName()));
try
{
retryTemplate.execute( c -> slackMessageSender.send(context));
LOG.debug(String.format("Successfully sent Slack notification for instance '%s'.", newInstance.getInstanceId()));
return true;
}
catch(IOException e)
{
LOG.debug(String.format("Failed to send Slack notification for instance '%s'.", newInstance.getInstanceId()));
return false;
}
目前该方法返回true,但我想让它抛出 IOException 并返回 false。如何模拟这种行为?
【问题讨论】:
标签: spring unit-testing mocking easymock spring-retry