简体   繁体   English

JUnit异常处理测试

[英]JUnit Exception Handling Test

In DAO class 在DAO班

catch (Exception e) {

        throw new DaoException(e);
}

In Junit Class 初级班

@Test
public void testClass() throws DaoException {
    try {
        doThrow(Exception.class).when(testDAO).getTestData();
        testDAO.getTestData();
    } catch (Exception e) {
        e.printStackTrace();

    }

}

Unable to cover DaoException.Could you please help me to cover DAOException in JUNIT. 无法涵盖DaoException。请您帮我涵盖JUNIT中的DAOException。

You should NOT enclose it in try catch block within your JUnit. 您不应将其放在JUnit的try catch块中。 Looks like you want to verify whether DaoException class being thrown. 看起来您想验证是否抛出了DaoException类。

Since you are already using JUnit 4, below is the syntax for it: 由于您已经在使用JUnit 4,因此其语法如下:

@Test(expected=DaoException.class)
public void testClass() {
    doThrow(Exception.class).when(testDAO).getTestData();
    testDAO.getTestData();
}

The snippet above will pass the test if it throws DaoException. 上面的代码段如果抛出DaoException,将通过测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM