Skip to content

Instantly share code, notes, and snippets.

@adityarama1210
Created March 11, 2021 03:32
Show Gist options
  • Save adityarama1210/ae9c93ef9b21b3049b2f037a3ad82467 to your computer and use it in GitHub Desktop.
Save adityarama1210/ae9c93ef9b21b3049b2f037a3ad82467 to your computer and use it in GitHub Desktop.
User Test Example
package user
import (
"database/sql"
"errors"
"reflect"
"testing"
)
func Test_GetUserProfile(t *testing.T) {
tests := []struct {
name string
userID int
mockFunc func()
expectedProfile UserProfile
expectingErr bool
}{
{
name: "All success no error",
userID: 10,
mockFunc: func() {
GetPersonByID = func(id int) (*Person, error) {
return &Person{
ID: 10,
BornDate: "1989-12-12",
Name: "Jack",
}, nil
}
GetPersonAddrByUserID = func(userID int) (*Address, error) {
return &Address{
ID: 123,
UserID: 10,
PostalCode: "12320",
Street: "Jl. XYZ, No 24, ABC, EFG",
}, nil
}
},
expectedProfile: UserProfile{
User: Person{
ID: 10,
BornDate: "1989-12-12",
Name: "Jack",
},
Address: Address{
ID: 123,
UserID: 10,
PostalCode: "12320",
Street: "Jl. XYZ, No 24, ABC, EFG",
},
},
expectingErr: false,
},
{
name: "Error in get person by id",
userID: 10,
mockFunc: func() {
GetPersonByID = func(id int) (*Person, error) {
return nil, sql.ErrConnDone
}
GetPersonAddrByUserID = func(userID int) (*Address, error) {
return &Address{
ID: 123,
UserID: 10,
PostalCode: "12320",
Street: "Jl. XYZ, No 24, ABC, EFG",
}, nil
}
},
expectedProfile: UserProfile{},
expectingErr: true,
},
{
name: "Error in get person address by user id",
userID: 10,
mockFunc: func() {
GetPersonByID = func(id int) (*Person, error) {
return &Person{
ID: 10,
BornDate: "1989-12-12",
Name: "Jack",
}, nil
}
GetPersonAddrByUserID = func(userID int) (*Address, error) {
return nil, sql.ErrConnDone
}
},
expectedProfile: UserProfile{},
expectingErr: true,
},
}
// preserve the original function
oriGetPersonByID := GetPersonByID
oriGetPersonAddrByUserID := GetPersonAddrByUserID
for _, tc := range tests {
t.Run(tc.name, func(tt *testing.T) {
tc.mockFunc()
up, err := GetUserProfile(tc.userID)
errExist := err != nil
if tc.expectingErr != errExist {
tt.Errorf("Error expectation not met, want %v, got %v", tc.expectingErr, errExist)
}
if !reflect.DeepEqual(tc.expectedProfile, up) {
tt.Errorf("Error, user profile expectation not met, want %+v, got %+v", tc.expectedProfile, up)
}
})
}
GetPersonByID = oriGetPersonByID
GetPersonAddrByUserID = oriGetPersonAddrByUserID
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment