期望不匹配:Golang 单元测试错误

Posted

技术标签:

【中文标题】期望不匹配:Golang 单元测试错误【英文标题】:Expectations unmatched : Golang unit test error 【发布时间】:2021-12-26 19:23:54 【问题描述】:

我是 Golang 的新手,当我尝试在测试用例下运行时遇到错误。有人可以建议我在这里做错了什么吗?

db, mock, _ := sqlmock.New()

    dbConnect, _ := services.DB.Connect(services.Config.Database)
    defer db.Close()

    rows := sqlmock.NewRows([]string"id", "txid", "nounce", "amount", "confirmations", "fromAddress", "toAddress", "toAccountId", "currencyId",
        "processStateId", "transactionTypeId", "transactionFees", "gasPrice", "gasLimit", "transactionIndex", "logIndex", "gasUsed",
        "status", "blockNumber", "createdAt", "updatedAt").
        AddRow("039f79c1-dbb3-4439-b9f7-361c7db6e03f", "0x642ec5ca327d0e64e958b1f9a6ef1feb61f0e541629b3769e854608d00d89744", 0, 0.01, 12, "0x3ee9f8c6a2676f2b0ebc324747253a23b7dbd1b3",
            "0x06fcd7f32e155be895ed9282446864e7397ae40d", "77c93121-5a9a-48fa-8c2f-23ff1debc3df", 2, 3, 2, 0.001, 0.001, 210000, 0, 0, 0, 0, 0, "2021-10-30 07:38:03.299+00", "2021-10-30 07:38:03.299+00").
        AddRow("039f79c1-dbb3-4439-b9f7-361c7db6e03f", "0x642ec5ca327d0e64e958b1f9a6ef1feb61f0e541629b3769e854608d00d89744", 0, 0.01, 12, "0x3ee9f8c6a2676f2b0ebc324747253a23b7dbd1b3",
            "0x06fcd7f32e155be895ed9282446864e7397ae40d", "77c93121-5a9a-48fa-8c2f-23ff1debc3df", 2, 3, 2, 0.001, 0.001, 210000, 0, 0, 0, 0, 0, "2021-10-30 07:38:03.299+00", "2021-10-30 07:38:03.299+00")

    GetTransactionsQuery(dbConnect, "25", "0")
    mock.ExpectQuery("SELECT * FROM BlockchainTransactions limit $1 offset $2").WithArgs("25", "0").WillReturnRows(rows)

    if err := mock.ExpectationsWereMet(); err != nil 
        t.Errorf("there were unfulfilled expectations: %s", err)
    
--- FAIL: Test_GetTransactionsQuery (7.79s)
    ethtransactions_test.go:51: there were unfulfilled expectations: there is a remaining expectation which was not matched: ExpectedQuery => expecting Query, QueryContext or QueryRow which:
          - matches sql: 'SELECT * FROM BlockchainTransactions limit $1 offset $2'
          - is with arguments:
            0 - 25
            1 - 0
          - should return rows:
            row 0 - [039f79c1-dbb3-4439-b9f7-361c7db6e03f 0x642ec5ca327d0e64e958b1f9a6ef1feb61f0e541629b3769e854608d00d89744 0 0.01 12 0x3ee9f8c6a2676f2b0ebc324747253a23b7dbd1b3 0x06fcd7f32e155be895ed9282446864e7397ae40d 77c93121-5a9a-48fa-8c2f-23ff1debc3df 2 3 2 0.001 0.001 210000 0 0 0 0 0 2021-10-30 07:38:03.299+00 2021-10-30 07:38:03.299+00]
            row 1 - [039f79c1-dbb3-4439-b9f7-361c7db6e03f 0x642ec5ca327d0e64e958b1f9a6ef1feb61f0e541629b3769e854608d00d89744 0 0.01 12 0x3ee9f8c6a2676f2b0ebc324747253a23b7dbd1b3 0x06fcd7f32e155be895ed9282446864e7397ae40d 77c93121-5a9a-48fa-8c2f-23ff1debc3df 2 3 2 0.001 0.001 210000 0 0 0 0 0 2021-10-30 07:38:03.299+00 2021-10-30 07:38:03.299+00]
FAIL

下面是我要模拟的函数:


func GetTransactionsQuery(db *sqlx.DB, limit string, offset string) ([]Transactions, error) 

    transactions := []Transactions
    Query := `SELECT *
    FROM "BlockchainTransactions"
    LIMIT :limit
    OFFSET :offset`
    params := map[string]interface
        "limit":  limit,
        "offset": offset,
    

    rows, err := db.NamedQuery(Query, params)

    for rows.Next() 
        transaction := Transactions
        rows.StructScan(&transaction)
        transactions = append(transactions, transaction)
    
    rows.Close()

    if err != nil 
        log.Fatalln(`GetTransactionsQuery: Failed to execute query`, err)
        return transactions, err
    

    return transactions, nil

编辑: 我在模拟数据之前调用了一个实际的函数;我仍然遇到同样的错误。

【问题讨论】:

设置期望值后,应先运行被测函数,然后再检查是否满足期望值。根据您的代码,您没有调用被测函数 感谢@BurakSerdar。我已经更新了我的代码。我仍然遇到同样的错误。如果我做错了,你能建议吗? 【参考方案1】:

@Burak Serdar 的意思是,您必须在实际调用触发模拟的函数之前声明您的期望。这意味着您的测试代码应该是

db, mock, _ := sqlmock.New()

dbConnect, _ := services.DB.Connect(services.Config.Database)
defer db.Close()

rows := sqlmock.NewRows([]string"id", "txid", "nounce", "amount", "confirmations", "fromAddress", "toAddress", "toAccountId", "currencyId",
    "processStateId", "transactionTypeId", "transactionFees", "gasPrice", "gasLimit", "transactionIndex", "logIndex", "gasUsed",
    "status", "blockNumber", "createdAt", "updatedAt").
    AddRow("039f79c1-dbb3-4439-b9f7-361c7db6e03f", "0x642ec5ca327d0e64e958b1f9a6ef1feb61f0e541629b3769e854608d00d89744", 0, 0.01, 12, "0x3ee9f8c6a2676f2b0ebc324747253a23b7dbd1b3",
        "0x06fcd7f32e155be895ed9282446864e7397ae40d", "77c93121-5a9a-48fa-8c2f-23ff1debc3df", 2, 3, 2, 0.001, 0.001, 210000, 0, 0, 0, 0, 0, "2021-10-30 07:38:03.299+00", "2021-10-30 07:38:03.299+00").
    AddRow("039f79c1-dbb3-4439-b9f7-361c7db6e03f", "0x642ec5ca327d0e64e958b1f9a6ef1feb61f0e541629b3769e854608d00d89744", 0, 0.01, 12, "0x3ee9f8c6a2676f2b0ebc324747253a23b7dbd1b3",
        "0x06fcd7f32e155be895ed9282446864e7397ae40d", "77c93121-5a9a-48fa-8c2f-23ff1debc3df", 2, 3, 2, 0.001, 0.001, 210000, 0, 0, 0, 0, 0, "2021-10-30 07:38:03.299+00", "2021-10-30 07:38:03.299+00")

//expect first
mock.ExpectQuery("SELECT * FROM BlockchainTransactions limit $1 offset $2").WithArgs("25", "0").WillReturnRows(rows)
// trigger your code
    GetTransactionsQuery(dbConnect, "25", "0")

if err := mock.ExpectationsWereMet(); err != nil 
    t.Errorf("there were unfulfilled expectations: %s", err)
 

最好通读一遍并了解如何使用go-sqlmock。

[建议] 同样在你的代码中先检查你的错误

func GetTransactionsQuery(db *sqlx.DB, limit string, offset string) ([]Transactions, error) 

    transactions := []Transactions
    Query := `SELECT *
    FROM "BlockchainTransactions"
    LIMIT :limit
    OFFSET :offset`
    params := map[string]interface
        "limit":  limit,
        "offset": offset,
    

    rows, err := db.NamedQuery(Query, params)
    // check error first
    if err != nil 
        log.Fatalln(`GetTransactionsQuery: Failed to execute query`, err)
        return transactions, err
    

    defer rows.Close()

    for rows.Next() 
        transaction := Transactions
        rows.StructScan(&transaction)
        transactions = append(transactions, transaction)
    

    return transactions, err
   

【讨论】:

以上是关于期望不匹配:Golang 单元测试错误的主要内容,如果未能解决你的问题,请参考以下文章

单元测试不了解 XCTest 期望的异步 UI 代码?

Golang - 用于解析 yaml 文件并检查对象的单元测试

Golang 单元测试矩阵在 SonarQube 仪表板上不可见

是否有设置 golang 单元测试参数的最佳实践?

如何使用不同的方法多次模拟调用 AWS 服务的 Golang 函数的单元测试?

golang 单元测试