dougu4704 2017-12-21 09:52
浏览 226
已采纳

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

I use go-sqlmock ( https://godoc.org/github.com/DATA-DOG/go-sqlmock ) to test a function that receives a variable number of arguments (I simplified the function for the sake of simplicity and stripped out most of the code):

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

The tests look like that:

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

Then I get this output:

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: ...

If I change the tests like this:

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

Then I get this output:

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:

The only I can make it pass is by calling :

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

which is what I obviously don't want to do as I don't know the number of actions...

Does anyone have an idea on how I could fix or debug this ?

0

2 条回答 默认 最新

查看更多回答(-1条)

报告相同问题?

悬赏问题

  • ¥15 如何在MPI程序中断点调试 求一个好用的代码注入器 三角波和正弦波经过加法电路,请问如何分离 windows 启动 hbase 遇到的问题 Failed construction RegionServer prometheus流量监控问题 戴尔g3玩饥荒游戏界面花屏 mongoose高并发,数据库操作过慢 怎么用matlab函数绘制pv曲线?