gpt4 book ai didi

go - 如何使用带有可变数量参数的 go-sqlmock WithArgs()?

转载 作者:IT王子 更新时间:2023-10-29 01:38:22 26 4
gpt4 key购买 nike

我使用 go-sqlmock ( https://godoc.org/github.com/DATA-DOG/go-sqlmock ) 来测试接收可变数量参数的函数(为了简单起见,我简化了函数并删除了大部分代码):

func getHits(db *sql.DB, actions ...string) (hits []Hit, err error) {
// ...
query := `select * from table where action in (?,?)`
rows, err := db.Query(query, actions)
// ...
}

测试看起来像这样:

// rows := ...
actions := []string{"click", "event"}
mock.ExpectQuery(`^select .*`).WithArgs(actions).WillReturnRows(rows)
hits, err := getHits(db, actions...)
if mockErr := mock.ExpectationsWereMet(); mockErr != nil {
log.Fatalf("there were unfulfilled expections: %s", mockErr)
}

然后我得到这个输出:

2017/12/21 10:38:23 there were unfulfilled expections: there is a remaining expectation which was not matched: ExpectedQuery => expecting Query or QueryRow which:
- matches sql: '^select .*'
- is with arguments:
0 - [click event]
- should return rows: ...

如果我这样更改测试:

mock.ExpectQuery(`^select .*`).WithArgs(actions[0], actions[1]).WillReturnRows(rows)

然后我得到这个输出:

2017/12/21 10:44:41 there were unfulfilled expections: there is a remaining expectation which was not matched: ExpectedQuery => expecting Query or QueryRow which:
- matches sql: '^select .*'
- is with arguments:
0 - click
1 - event
- should return rows:

我唯一能让它通过的方法是调用:

db.Query(query, actions[0], actions[1])

这显然是我不想做的,因为我不知道操作的数量...

有人知道我该如何解决或调试这个问题吗?

最佳答案

使用 []interface{} 的已接受答案适用于字符串,但它可能会引发其他类型的错误。

简答

actions := []driver.Value{"click", "event"}
mock.ExpectQuery(`^select .*`).WithArgs(actions...).WillReturnRows(rows)

长答案

参数需要driver.Value reference和 driver.Value 可以是其中之一 types :

  • int64
  • float64
  • bool
  • []字节
  • 字符串
  • 时间.时间

所以,正确答案是

actions := []driver.Value{"click", "event"}
mock.ExpectQuery(`^select .*`).WithArgs(actions...).WillReturnRows(rows)

关于go - 如何使用带有可变数量参数的 go-sqlmock WithArgs()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47922204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com