60 lines
1.0 KiB
Go
60 lines
1.0 KiB
Go
package gomock
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/stretchr/testify/assert"
|
|
"testing"
|
|
|
|
"go.uber.org/mock/gomock"
|
|
)
|
|
|
|
func TestGetUserName(t *testing.T) {
|
|
ctrl := gomock.NewController(t)
|
|
defer ctrl.Finish()
|
|
|
|
mockUserService := NewMockUserService(ctrl)
|
|
|
|
// 定义测试用例
|
|
testCases := []struct {
|
|
name string
|
|
userID int
|
|
mockSetup func()
|
|
expected string
|
|
err error
|
|
}{
|
|
{
|
|
name: "valid user",
|
|
userID: 1,
|
|
mockSetup: func() {
|
|
mockUserService.EXPECT().
|
|
GetUser(1).
|
|
Return(&User{ID: 1, Name: "Alice"}, nil)
|
|
},
|
|
expected: "Alice",
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "user not found",
|
|
userID: 2,
|
|
mockSetup: func() {
|
|
mockUserService.EXPECT().
|
|
GetUser(2).
|
|
Return(nil, errors.New("user not found"))
|
|
},
|
|
expected: "",
|
|
err: errors.New("user not found"),
|
|
},
|
|
}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
tc.mockSetup()
|
|
|
|
result, err := GetUserName(mockUserService, tc.userID)
|
|
|
|
assert.Equal(t, tc.expected, result)
|
|
assert.Equal(t, tc.err, err)
|
|
})
|
|
}
|
|
}
|