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

huangapple go评论90阅读模式
英文:

Expectations unmatched : Golang unit test error

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我是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
}

编辑:
在模拟数据之前,我调用了一个实际的函数,但仍然出现相同的错误。

英文:

I am new to Golang,I am getting below error when I try to run below testcase. Can someone please suggest what am I doing wrong here?

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

Below is the Function I am trying to mock:


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
}

Edit:
I am calling an actual function before I mock data; I am still getting same error.

答案1

得分: 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")

//先声明期望
mock.ExpectQuery("SELECT * FROM BlockchainTransactions limit $1 offset $2").WithArgs("25", "0").WillReturnRows(rows)
//触发你的代码
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)
    //先检查错误
    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
}
英文:

What @Burak Serdar means is that your expectations must be declared before you actually call your function that triggers mock. It means your test code should be

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)
}

It's better to go thrugh and understand how to use go-sqlmock.

[Suggestion] Also in your code check your error first

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
   }

huangapple
  • 本文由 发表于 2021年11月15日 23:32:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/69976907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定