我在类中编写了创建新类别的代码,如果找不到该类别,它将抛出“ CategoryNotFoundException”。我已经写了测试用例,但是没有通过。
如果我在JUNIT测试用例中省略了“ expected = CategoryNotFoundException.class”,它将通过。但是我不想更改测试用例中的任何部分。我尝试从实现的类中抛出异常,但仍然没有通过。我坚持在那里通过TestCase。
DAO code::
@Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
Session session=this.sessionFactory.getCurrentSession();
session.save(category);
return true;
//return isInserted;
}
也尝试了以下代码,但未通过TC:
@Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
try{
Session session=this.sessionFactory.getCurrentSession();
Integer isInsertedWrapper=(Integer)session.save(category);
if(isInsertedWrapper>0){
return true;
}else{
throw new CategoryNotFoundException("CategoryNotFoundException");
}
}
catch(Exception ex){
return false;
}
}
JUNIT代码::
@Test(expected= CategoryNotFoundException.class)
@Rollback(true)
public void testCreateCategoryFailure() throws CategoryNotFoundException {
categoryDAO.createCategory(category);
Category savedCategory = categoryDAO.getCategoryById(2);
assertNotEquals(category, savedCategory);`enter code here`
}
答案 0 :(得分:0)
您正在尝试引发异常,但同时也正在捕获,因此,如果有必要,您应该重新抛出,所以您应该尝试执行以下操作:
@Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
try {
Session session=this.sessionFactory.getCurrentSession();
Integer isInsertedWrapper=(Integer)session.save(category);
if(isInsertedWrapper>0){
return true;
}else{
throw new CategoryNotFoundException("CategoryNotFoundException");
}
} catch(CategoryNotFoundException exc) {
throw exc;
} catch(Exception ex){
return false;
}
}