简体   繁体   English

在Java中进行单元测试时,如何强制调用SQLException?

[英]How do I force call a SQLException when Unit Testing in Java?

I am running Java tests on JUnit 4.xx. 我正在JUnit 4.xx上运行Java测试。 I'm trying to force run a SQLException from the try block. 我试图从try块强制运行SQLException。 I've ran Mockito in many different ways but I don't get the result that I want. 我已经以许多不同的方式运行了Mockito,但我没有得到想要的结果。

Here is my main file: 这是我的主文件:

public boolean close()   {

    if (connection == null) {
        throw new IllegalStateException("Connection never initialized!");
    }

    try {
        connection.close();
        return true;
    }

    catch (SQLException e)
    {
        LOGGER.logp(Level.INFO, CLASS_NAME, "close", e.getMessage());
        return false;
    }

}

Here is my test file: 这是我的测试文件:

@Test
public void testFail2() throws SQLException {

    JDBCConnection spyConnect = mock(JDBCConnection.class);

    given(spyConnect.getConnection()).willAnswer(invocationOnMock -> new SQLException());

    assertFalse(spyConnect.close());
}

In summary, how do I get the catch block to get executed so that I get 100% line coverage for my overall program? 总之,如何使catch块执行,以便使整个程序获得100%的行覆盖率? Thanks for the help in advance. 我在这里先向您的帮助表示感谢。

如果要让模拟程序引发异常,则应使用willThrow ,而不是willAnswer

given(spyConnect.getConnection()).willThrow(new SQLException());

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

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