我正在为一个方法编写一个JUnit测试用例,为了增强我的Cobertura分支复盖率,我想捕获异常,但不确定为什么测试没有捕获异常。
测试方法:
public void getCondition( Map<String, Message> messagesMap ) throws EISClientException
{
Message message = containsAMessageCode(getMessageCodes(), messagesMap);
if(message!=null)
{
throw new EISClientException("One of the specified message code matched returned errors." +
message.getMessageCode() + ": " + message.getMessageType() + ": " + message.getMessageText());
}
}JUnit测试:
@Test
public void testgetCondition() throws Exception {
boolean caughtException = false;
try {
clientResponse = mock(ClientResponse.class);
RetrieveBillingServiceResponse response = new RetrieveBillingServiceResponse();
MessageToExceptionPostProcessFilter postProcessFilter = new MessageToExceptionPostProcessFilter();
postProcessFilter.setCondition(ConditionOperator.OR);
Message message = new Message();
message.setMessageCode("200");
message.setMessageType(MessageTypeEnum.MESSAGE_TYPE_INFO);
message.setMessageText("Service completed successfully");
response.setMessages(Arrays.asList(message));
Map<String, Message> map = new HashMap<String, Message>();
map.put("test", message);
RetrieveBillingServiceResponse serviceResponse = postProcessFilter.getCondition(map);
} catch (EISClientException ex) {
caughtException = true;
assertEquals("One of the specified message code matched returned errors.", ex.getMessage());
}
assertTrue(caughtException);
}如果消息不为空,它应该捕获异常,但它不是。我做错什么了吗?
谢谢,
发布于 2016-02-04 06:23:45
测试被抛出的预期异常的另一种方法是在导致异常的被测代码行之后添加一个fail()。
如果抛出异常,则跳转到捕获并永远不调用fail();如果没有抛出异常,则将在本应抛出异常的行后执行fail(),并且测试失败。
此外,请查看当前的assertEquals() -您正在比较的字符串与创建异常时正在构建的字符串不同。
发布于 2016-02-04 06:21:09
发布于 2016-02-04 06:29:44
你确定你的测试调用了getCondition()方法吗?我在你的代码中看不到它。但是,如果您确定调用了getCondition(),请尝试使用!message.isEmpty()而不是message!=null
https://stackoverflow.com/questions/35188743
复制相似问题