java - JUNIT 测试用例未通过

标签 java hibernate junit

我有一个类,我在其中编写代码来创建新类别,如果找不到类别,它将抛出“CategoryNotFoundException”。我已经写了测试用例,但没有通过。

如果我从 JUNIT 测试用例中省略“expected= CategoryNotFoundException.class”,它将通过。但我不想更改测试用例中的任何部分。我尝试从我实现的类中抛出异常,但它仍然没有通过。我坚持在那里通过测试用例。

    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`

        }

最佳答案

你试图抛出一个异常,但你也在捕获异常,所以你应该重新抛出如果有必要,那么你应该尝试这样做:

@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;
    } 
}

关于java - JUNIT 测试用例未通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57643310/

相关文章:

java - Spring引导+JUnit 5 : cannot globally set test instance lifecycle

java - 在 Tomcat 上成功部署我的项目,但无法请求。显示 404

java - 嵌入 Tomcat-7 以仅在 https 中运行

java - Hibernate 中的嵌套 createAlias()

mysql - Grails 2.4.4 : Database record updates on createCriteria(). 列表()

java - 在 Espresso Java/Android 中等待匹配器

Java:调用静态方法但没有任何反应?

java - 如何创建一个用户闲置5分钟后弹出的对话框? ( java )

hibernate - 如何、何时何地在 hbm 文件中使用自然 ID?

java - SpringBoot ArrayIndexOutOfBoundsException MethodParameter.getGenericParameterType