【发布时间】:2014-06-17 19:22:27
【问题描述】:
以下是代码,我想知道如何编写 JUnit 测试,以便我的覆盖范围可以覆盖 catch 块
import com.pkg.ClothBrandQuery;
Public class MapBrand implements SomeInterface{
public Brand mapThisBrands(final ClothBrand clothBrand) {
Brand brand = new Brand();
try{
defaultBrand = clothBrandQuery.getClothBrandMethod(ProjectConstants.DEFAULT_BRAND_KEY);
}
catch(Exception e){
logger.fatal("Database error occurred retrieving default cloth brands", e);
System.exit(2);
}
if(defaultBrand != null && defaultBrand != clothBrand){
brand.setBrandName(clothBrand.getBrandName());
brand.setCompanyName(clothBrand.getCompanyName());
brand.setBackgroundColor(clothBrand.getBackgroundColor());
}
else{
brand.setBrandName(defaultBrand.getBrandName());
brand.setCompanyName(defaultBrand.getCompanyName());
brand.setBackgroundColor(defaultBrand.getBackgroundColor());
}
}
}
我能够为 mapThisBrands 编写测试方法来测试品牌对象,但我不知道如何测试 defaultBrand 对象以及如何编写将执行 catch 块的测试用例。
【问题讨论】:
-
避免在除顶级
main()方法之外的任何地方使用System.exit(),其唯一目的是返回退出代码。在所有其他情况下始终使用异常。见javapractices.com/topic/TopicAction.do?Id=86。