接口測試的重要性,這個不大篇幅描述了,講一講接口測試時異常情況的測試方案吧。
在開發(fā)代碼中,經常會有獲取異常,捕獲異常的情況,在進行接口測試的時候,往往會覆蓋異常情況。那么異常情況的exception校驗也變成必要了。junit提供了一個方法直接獲取exception,校驗exception。
下面具體講講如何測試吧。
被測代碼如下:
public long punishMemberWithRule(Long memberId, String punishRule, String operator)
throws ManagerException {
if (memberId == null || punishRule == null) {
throw new ManagerException("處罰會員傳入的會員Id: " + memberId
+ " punishRule: " + punishRule + "為空");
}
PunishRequestDO requestDO = new PunishRequestDO();
requestDO.setOperator(operator); //操作人
requestDO.setUserId(memberId);
requestDO.setAppName("Rhine");
requestDO.setRuleCode(punishRule); //
PunishResult punishResult = null;
try {
punishResult = punishExecuteClient.punish(requestDO);
log.error("[PunishMember] 處罰會員: " + memberId + " 使用的code為 "
+ punishRule + " 處罰結果id: " + punishResult.getResultId());
} catch (Exception e) {
throw new ManagerException("調用puniExecuteClient處罰會員失敗", e);
}
if (punishResult == null || punishResult.getResultId() == 0) {
throw new ManagerException(punishResult.getMessage());
}
return punishResult.getResultId();
}
看代碼知道,這邊會有拋異常的情況,那么如何測試呢?
下面為異常情況的測試代碼:
@Rule
public ExpectedException expectedEx =ExpectedException.none();
@Test
public void test01_memberIdisNull() throws ManagerException{
expectedEx.expect(ManagerException.class);
expectedEx.expectMessage("處罰會員傳入的會員Id:");
expectedEx.expectMessage("為空");
Long memberId=null;
String punishRule=null;
String perator=null;
pcManager.punishMemberWithRule(memberId,punishRule,operator);
}
獲取exception類,及校驗exception對應的message。這個異常測試完成了。
原理:junit4 @Rule注解下Exception實現(xiàn)了MethodRule,對拋出的異常進行了捕獲,通過expect方法與執(zhí)行中的exception類進行對比。主要是junit rules實現(xiàn)了ExpectedException類。具體原理還需要研讀junit4源碼才能知曉其更深入的原理。