【发布时间】:2021-04-12 07:54:58
【问题描述】:
我基本上想要的是全面覆盖下面的代码sn-p
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;
}
我想模拟一个 SQLException throw 到 getDbConnection 中,以便它也涵盖捕获场景,这就是我到目前为止所拥有的。
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());
}
当我尝试通过 junit 进行代码覆盖时,仍然没有覆盖 catch 场景,并导致“检查的异常对此方法无效”
我已经尝试过来自 stackoverflow 的其他可能的论坛,但没有一个对我有用。
【问题讨论】: