Unit testing 正在获取数据库连接的连接字符串

Unit testing 正在获取数据库连接的连接字符串,unit-testing,go,Unit Testing,Go,我正在尝试测试此函数: //OpenConnection opens a connection to a MySQL database by `connStr` // or returns error. If `connStr` is empty, error is returned. // // Parameters: // - `connStr`: the URL of the database to connect to // - `interpolateParams` : should

我正在尝试测试此函数:

//OpenConnection opens a connection to a MySQL database by `connStr`
// or returns error. If `connStr` is empty, error is returned.
//
// Parameters:
// - `connStr`: the URL of the database to connect to
// - `interpolateParams` : should we interpolate parameters?
//
// Returns:
// - pointer to the database connection
// - any errors that happened during this process
func OpenConnection(connStr string, interpolateParams bool) (*sql.DB, *errors.ErrorSt) {
    if connStr == "" {
        return nil, errors.Database().ReplaceMessage("No database connection string.")
    }
    connStr = connStr + "?parseTime=true&multiStatements=true"
    if interpolateParams {
        connStr += "&interpolateParams=true"
    }

    db, err := sql.Open("mysql", connStr)
    if err != nil {
        return nil, errors.Database().AddDetails(err.Error(), connStr)
    }
    return db, nil
}
对于
插值图的情况
。我正在筛选,没有找到从
sql.DB
获取连接字符串的简单方法。因为这是单元测试,所以我当然是在用一个假连接URL访问函数


是否有方法从
sql.DB
获取连接URL以检查插值查询字符串?
数据库/sql
主要关注的是作为使用sql进行操作的接口。连接字符串通常是特定于驱动程序的,因此我会查看您使用的驱动程序,以了解如何在您的案例中获取连接字符串,根据顶部的注释判断,您使用的是MySQL,因此我假设您将使用
go sql驱动程序/MySQL
。您可以直接在代码中导入它(而不是使用空白导入),并访问
Config
struct,这里有文档记录:它从传入
sql的dsn中填充。Open

只需将该逻辑移到构建连接字符串的函数中,并进行单元测试。我必须获得boss的许可才能这样做。(我只负责单元测试和文档编制。)如果你负责编写测试而不是代码,那是非常不幸的情况(这是一种客观上非常糟糕的操作方式),但我想你可以为不存在的连接字符串构建函数编写测试,让测试失败,直到开发人员更改代码。@Adrian好消息:老板告诉我不要担心