2017-12-21 13 views
0

내가 가서-sqlmock (https://godoc.org/github.com/DATA-DOG/go-sqlmock)를 가변 인자를받는 함수를 테스트하는 데 사용 (I 간단하게하기 위해 기능을 단순화하고 코드의 대부분을 제거) :go-sqlmock WithArgs()를 가변 개수의 인수와 함께 사용하는 방법?

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

테스트 모습 나는이 같은 테스트를 변경하는 경우

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

: : 그런 :

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

은 내가 통과 할 수있다 :

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

은 그 때 나는이 출력을 얻을

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

나는 분명히 내가 같이하고 싶지 않아 무엇 인 행동의 수를 모른다 ...

누구나 내가 이것을 고칠 수 있거나 어떻게 디버그 할 수 있는지에 대한 생각을 갖고 있니?

+0

입니다.'actions ...'가 작동하지 않습니까? – Flimzy

+0

@Flimzy nope; ("^ select. *") .Args' – Cyrille

+0

'actions'를'[] 드라이버로 변환하십시오. "컴파일러는 다음과 같이 불평합니다 :'type [] string으로 동작을 사용할 수 없습니다. 그때 가치. – Flimzy

답변

0
내 문제를 해결하는 방법을 발견

: 나는 db.Query에 대한 인터페이스의 슬라이스에 문자열의 조각을 변환하면, 그것은 잘 작동 : 테스트를 위해 그

boundValues := make([]interface{}, len(actions)) 

for i, val := range actions { 
    boundValues[i] = val 
} 

rows, err := db.Query(query, boundValues...) 

:

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

참고 : 단지 db.Query(query, actions...)을 전달하면 작동하지 않습니다. 이 결과는 cannot use actions (type []string) as type []interface {} in argument to db.Query