This is an automated archive.
The original was posted on /r/golang by /u/Elephant_In_Ze_Room on 2023-09-01 13:53:30+00:00.
Hey all.
How does one go about testing sqlx Select queries? Ideally I would like to do dependency injection if that makes sense?
I’m pretty good at passing Interfaces into functions and using that to mock out the API response with dependency injection. Something like the below where I would be testing a function that has an api
input which would be a slack client which has a method GetUserGroups
// Function and Interface
type slackGroupReader interface {
GetUserGroups(...slack.GetUserGroupsOption) ([]slack.UserGroup, error)
}
func getSlackGroups(users map[string]User, api slackGroupReader) (map[string]User, error) {}
// mocks of GetUserGroups
type mockGetUserGroups struct {
Response []slack.UserGroup
}
func (m mockGetUserGroups) GetUserGroups(...slack.GetUserGroupsOption) ([]slack.UserGroup, error) {
return m.Response, nil
}
// This would be then be the input for `api` in my test, this allows me to prevent API calls from being sent and instead
// write the response as desired.
mockGetUserGroups{
Response: []slack.UserGroup{
{
ID: "foo",
Name: "car",
Users: []string{"bar"},
},
{
ID: "foo",
Name: "dar",
Users: []string{"bar"},
},
},
},
I haven’t done a ton of sql before and I’m wondering how I should test a function. I would also prefer to use the standard library unless there’s a go to library that is up to date and makes life easier.
Right now two things are happening in the function:
- The db connection is being created (this can be moved to a separate function easily)
- The connection object is used to make a select query which fills in a []Struct object.
The code looks like this:
func getUsers() (map[string]User, error) {
db, err := sqlx.Connect("postgres", "blah=blah")
if err != nil {
return nil, err
}
defer db.Close()
query := "SELECT * FROM table;")
var rotations []Rotation
err = db.Select(&rotations, query)
if err != nil {
return nil, err
}
users := map[string]User{}
for _, rotation := range rotations {
users[rotation.Name] = User{Email: rotation.Email}
}
return users, nil
}
How should I go about testing it? The pattern differs from what I usually do with APIs because here Select()
writes to a destination parameter (&rotations
) rather than returning the results (which would make it really easy to mock with standard dependency injection).
Also wondering if I should instead just use the sql standard library as that appears to return Rows that I can put in my struct.