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.