How to use mock code in unit test

定義 test suite

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
// biz_test.go

// declare test suite struct
type bizSuite struct {
suite.Suite
mock *mocks.IRepo
biz IBiz
}

// setup test suite
func (s *bizSuite) SetupTest() {
logger, _ := zap.NewDevelopment()
node, _ := snowflake.NewNode(1)
factory, _ := token.New(&token.Options{Signature: "7d01eb0200bc730a2c58"}, logger)

s.mock = new(mocks.IRepo)
if biz, err := CreateIBiz(logger, s.mock, node, factory); err != nil {
panic(err)
} else {
s.biz = biz
}
}

// teardown test suite
func (s *bizSuite) TearDownTest() {
s.mock.AssertExpectations(s.T())
}

func TestBizSuite(t *testing.T) {
suite.Run(t, new(bizSuite))
}

撰寫測試

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
func (s *bizSuite) Test_impl_GetByID() {
type args struct {
ctx contextx.Contextx
id int64
mock func()
}
tests := []struct {
name string
args args
wantInfo *user.Profile
wantErr bool
}{
{
name: "get by id then error",
args: args{id: id1, mock: func() {
s.mock.On("GetByID", mock.Anything, id1).Return(nil, errors.New("error")).Once()
}},
wantInfo: nil,
wantErr: true,
},
{
name: "get by id then not exists",
args: args{id: id1, mock: func() {
s.mock.On("GetByID", mock.Anything, id1).Return(nil, nil).Once()
}},
wantInfo: nil,
wantErr: true,
},
{
name: "get by id then user",
args: args{id: id1, mock: func() {
s.mock.On("GetByID", mock.Anything, id1).Return(info1, nil).Once()
}},
wantInfo: info1,
wantErr: false,
},
}
for _, tt := range tests {
s.T().Run(tt.name, func(t *testing.T) {
if tt.args.mock != nil {
tt.args.mock()
}

gotInfo, err := s.biz.GetByID(tt.args.ctx, tt.args.id)
if (err != nil) != tt.wantErr {
t.Errorf("GetByID() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotInfo, tt.wantInfo) {
t.Errorf("GetByID() gotInfo = %v, want %v", gotInfo, tt.wantInfo)
}

s.TearDownTest()
})
}
}