...
Code Block |
---|
language | text |
---|
theme | FadeToGrey |
---|
|
// Interface for imported packages
type ImageManagerImportsService interface {
GetCurrentUser() (*user.User, error)
} |
Let's make ImageCLient use ImportsService to get user. So, ImageClient implements and uses ImportsService.
Code Block |
---|
language | text |
---|
theme | FadeToGrey |
---|
|
type ImageClient struct {
user ImportsService
storeName string
tagMeta string
} |
Let's rewrite GetDirPath to use GetCurrentUser.
Code Block |
---|
language | text |
---|
theme | FadeToGrey |
---|
|
func (v *ImageClient) GetDirPath(imageName string) (string, string, error) {
u, err := v.GetCurrentUser()
home := u.HomeDir
dirPath := path.Join(home, "images", v.storeName)
filePath := path.Join(dirPath, imageName)
return filePath, dirPath, err
} |
Let's define GetCurrentUser on ImageClient.
Code Block |
---|
language | text |
---|
theme | FadeToGrey |
---|
|
// define GetCurrentUser
func (v *ImageClient) GetCurrentUser() (*user.User, error) {
u, err := user.Current()
if err != nil {
return nil, pkgerrors.Wrap(err, "Current user")
}
return u, nil
} |
To test GetDirPath using testify mock, let's re-write image_test.go
Code Block |
---|
language | text |
---|
theme | FadeToGrey |
---|
|
package app
import (
"fmt"
"os/user"
"testing"
"github.com/stretchr/testify/mock"
)
type mockImports struct {
mock.Mock
}
func (m *mockImports) GetCurrentUser() (*user.User, error) {
fmt.Println("Mocked Get User")
args := m.Called()
return args.Get(0).(*user.User), args.Error(1)
}
func TestService(t *testing.T) {
fakeUser := &user.User{}
myImports := new(mockImports)
myImports.On("GetCurrentUser").Return(fakeUser, nil)
imageClient := ImageClient{myImports, "test_image", "test_meta"}
_, dir, err := imageClient.GetDirPath("test")
if err != nil {
t.Errorf("Path was incorrect, got: %q, want: %q.", dir, "some_path")
}
} |
With GetCurrentUser defined on mockImports, inside my TestService, I choose the mockImports object for testing:
Code Block |
---|
language | text |
---|
theme | FadeToGrey |
---|
|
imageClient := ImageClient{myImports, "test_image", "test_meta"} |
Run:
go test -v
References:
- https://restfulapi.net/rest-architectural-constraints/
...