Skip to content

Instantly share code, notes, and snippets.

@darland
Created April 6, 2020 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darland/a085cbf797bbd26e00f1d4949d3ac02a to your computer and use it in GitHub Desktop.
Save darland/a085cbf797bbd26e00f1d4949d3ac02a to your computer and use it in GitHub Desktop.
Example of unit-test on golang using testify
package example
type User struct {
ID string
Email string
}
type SomeAPIClient interface {
GetUser(usedId string) (*User, error)
}
func getUser(c SomeAPIClient, userID string) (*User, error) {
return c.GetUser(userID)
}
package example
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type FakeClient struct {
mock.Mock
}
func (f FakeClient) GetUser(usedId string) (*User, error) {
args := f.Called(usedId)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*User), args.Error(1)
}
func TestClient(t *testing.T) {
assert := assert.New(t)
testClient := new(FakeClient)
testClient.On("GetUser", "error").Return(nil, errors.New("error"))
u, err := getUser(testClient, "error")
assert.Nil(u)
assert.EqualError(err, "error")
testUser := &User{ID: "user"}
testClient.On("GetUser", "user").Return(testUser, nil)
u, err = getUser(testClient, "user")
assert.Equal(testUser, u)
assert.Nil(err)
testClient.AssertExpectations(t)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment