Search code examples
javajunitmockito

Check exception invalid for Mockito SQLException throw


What i basically want is to have a full coverage for the code snippet below

public Connection getDbConnection() {
    Logger logger = LoggerFactory.getLogger("DatabaseConnection.class");
    PropertyUtility propUtility = new PropertyUtility();
    Properties prop = propUtility.getDbProperty();
    Connection conn = null;
    try
    {
        final String dbUrl = prop.getProperty("db.url");
        final String dbUsername = prop.getProperty("db.user");
        final String dbPassword = prop.getProperty("db.password");

        conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
    }
   catch (SQLException ex)
    {
           logger.error("Cannot connect to database server");
           logger.error(ex.getMessage());
    }      
    return conn;
}

I want to mock an SQLException throw into the getDbConnection for it to cover the catch scenario as well and here's what i have so far.

DatabaseUtility db = new DatabaseUtility();
DatabaseUtility dbMock;
void setUp() throws Exception {
    dbMock = mock(DatabaseUtility.class);
}
@Test
final void testGetDbPropertyFail () {
    when(dbMock.getDbConnection()).thenThrow(new SQLException("TEST"));
    assertEquals(null,db.getDbConnection());
}

When i try to do a code coverage via junit, the catch scenario is still not covered and it results with "Checked exception is invalid for this method"

I've tried other possible forums from stackoverflow and none have worked for me.


Solution

  • I guess the getDbConnection() is a method of DatabaseUtility, and you want to unit test DatabaseUtility class, right?

    The "Checked exception is invalid for this method" is as literal as it gets, which means that Mockito only allows the mock to throw Runtime exceptions.

    What's more, you may use verify() method provided by Mockito to verify state changing or times-be-called of mocked objects. (And, sorry for any offense, mock means virtualizating other relative modules of the target test module, but leave the target not being mocked so it will go through real logic in code, not fake interfaces provided by unit testing library.)

    What is Mocking?

    https://www.baeldung.com/mockito-verify