-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathapi_test.go
84 lines (69 loc) · 2.18 KB
/
api_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package api
import (
"errors"
"testing"
"github.com/cybersamx/go-recipes/fake-mock/api/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestAPIUsingFake(t *testing.T) {
// Setup
fam := mocks.NewFakeAccountModel()
service := NewAccountService(fam)
// Run
pwd, err := service.ForgotPassword(email)
// Validation
assert.NoError(t, err)
assert.NotEmpty(t, pwd)
foundAcct, err := fam.GetAccount(email)
assert.NoError(t, err)
assert.NotNil(t, foundAcct)
assert.Equal(t, pwd, foundAcct.Password)
}
func TestAPIUsingMock(t *testing.T) {
// Setup
mam := mocks.NewTestifyMockAccountModel()
service := NewAccountService(mam)
mam.On("UpdateAccount", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(nil)
mam.On("AddAccount", mock.Anything, mock.Anything).Return(func(e, pwd string) error {
// The following is strictly for demo. It doesn't make logic sense.
if e == email {
return nil
}
return errors.New("mismatched password")
})
// We can call the mocks directly. For this, instead of passing a literal value to
// Return(), we can pass a function. To do so, we need to change the mocked AddAccount.
assert.NoError(t, mam.AddAccount(email, "my-password"))
assert.Error(t, mam.AddAccount("wrong-email", "my-password"))
// Run
// Note: service.ForgotPassword is the actual code that we are unit testing.
pwd, err := service.ForgotPassword(email)
// Validation
assert.NoError(t, err)
assert.NotEmpty(t, pwd)
// Asset that the expectations were met
mam.AssertExpectations(t)
}
func TestAPIUsingMockgen(t *testing.T) {
// Setup
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mam := mocks.NewMockAccountModel(ctrl)
service := NewAccountService(mam)
mam.EXPECT().
UpdateAccount(email, gomock.Any()).
Return(nil)
// Run
// Note: service.ForgotPassword is the actual code that we are unit testing.
pwd, err := service.ForgotPassword(email)
// Validation
assert.NoError(t, err)
assert.NotEmpty(t, pwd)
}