Created
April 6, 2020 08:36
-
-
Save darland/a085cbf797bbd26e00f1d4949d3ac02a to your computer and use it in GitHub Desktop.
Example of unit-test on golang using testify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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