duanou3868
duanou3868
2017-02-15 15:37
浏览 53
已采纳

可测试的数据库/ SQL sql.Rows

Is there a good practice for testing/mocking functions that perform the scanning of sql.Rows into structs.

func parseUsers(r *sql.Rows) (users []User, err error) {
    for r.Next() {
        var u User
        if err = r.Scan(&u.Username,
            &u.DisplayName,
            &u.EmailAddress,
            &u.IsEnabled,
            &u.PhoneNumber); err != nil {
            return []User{}, err
        }
        users = append(users, u)
    }
    err = r.Err()
    return
}

But trying to do something like:

func TestParseUsers(t *testing.T) {
    //make mock sql.Rows
    u, err := parseUsers(fakeRows)
    //Do tests...
}

I have looked at sqlx, but would like to keep the database/sql structure. And I checked go-sqlmock, but I am looking for something without a large build up.

Is there a good strategy for this sort of test?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douqiang4245
    douqiang4245 2017-02-15 16:21
    已采纳

    The go way would be to use an interface as input.

    In your case it could look like this:

    type Scanner interface {
      Next()
      Scan(User)
    }
    

    The function should look like this:

    func parseUsers(s Scanner) (users []User, err error) {
      // ...
    }
    

    Now testing is very easy, because you can create a mock scanner, which implements the interface and remembers, with which parameters the methods has been called.

    点赞 评论

相关推荐