我有一个有这个方法的静态类:
public static Connection getDbConnection(String tenant, String product) {
Connection connection = null;
try {
Map<String,Map<String,String >> databaseConnectionTable = PropertyUtil.getInstance().getDatabaseConnectionTable();
Map<String,String> properties = getHighestPrecedenceMap(databaseConnectionTable,tenant,product);
if (properties!=null) {
Class.forName(properties.get("db.driver"));
connection = DriverManager.getConnection(
properties.get("db.url"),
properties.get("db.user"),
properties.get("db.password"));
}
} catch (ClassNotFoundException e) {
LOGGER.error("Message",e);
} catch (SQLException e) {
LOGGER.error("Message:",e);
}
return connection;
}
然后我有另一个类,它有一个方法来获取给定 SQL 查询字符串的结果集,这个方法调用上面的方法,下面是源代码:
public static ResultSet getResultSetFromSql(String sql,String tenant,String product) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
try {
if(product!=null)
connection = SqlConnectionUtil.getDbConnection(tenant,product);
RccSqlParameterMap parameterMap = RccSqlParameterMap.getParameterMap();
if(connection!=null) {
if (parameterMap.getSqlParameters().entrySet().size() > 0)
sql = parameterMap.SqlMessageFormat(sql);
else
LOGGER.error("Parameter map isn't set please initialize it");
LOGGER.info("Executing SQL: " + sql);
statement = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
if (!statement.execute()) {
LOGGER.error("No results found for statement!");
return null;
}
rs = statement.getResultSet();
}else{
LOGGER.error("Coudn't create Connection Object");
}
} catch (SQLException e) {
LOGGER.error("Message", e);
}
return rs;
}
我需要编写单元测试来测试这些,以便在内存中实现我能够通过从文件中读取行来模拟结果集,所以当我实例化结果集模拟器并执行 getResultSet( )
我得到了结果集对象,我面临的问题是将这个 mocker 与上述方法集成。请建议一种方法。
最佳答案
您可以直接在测试用例的代码中指定模拟数据,无需从文件系统中读取任何内容。
使用 Mockito,您可以使对象的方法返回您想要的任何内容:
// Initialize the object to be returned
ResultSet desiredResultSet = ...;
// After doing this you can mock methods of statement object
statement = Mockito.mock(PreparedStatement.class);
// Whenever you call statement.getResultSet(), it will return desiredResultSet
Mockito.doReturn(desiredResultSet).when(statement).getResultSet();
要使用此机制,您唯一需要更改代码的是使 Connection
可用于您的测试代码。这样您就可以像我上面演示的那样模拟它返回 PreparedStatement
的方法。
总的来说,我建议您将您的方法拆分为一些较小的方法 - 现在它们有太多的事情需要一个方法进行。这也将使您的代码更容易进行单元测试和模拟。
关于java - 使用 mockito 模拟结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45810312/