121 lines
2.8 KiB
Go
121 lines
2.8 KiB
Go
package commentservicelogic
|
|
|
|
import (
|
|
"app-cloudep-tweeting-service/gen_result/pb/tweeting"
|
|
model "app-cloudep-tweeting-service/internal/model/mongo"
|
|
"app-cloudep-tweeting-service/internal/svc"
|
|
"context"
|
|
"errors"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
"go.uber.org/mock/gomock"
|
|
|
|
mocklib "app-cloudep-tweeting-service/internal/mock/lib"
|
|
mockmodel "app-cloudep-tweeting-service/internal/mock/model"
|
|
)
|
|
|
|
func TestGetComments(t *testing.T) {
|
|
ctrl := gomock.NewController(t)
|
|
defer ctrl.Finish()
|
|
|
|
// 初始化 mock 依賴
|
|
mockCommentModel := mockmodel.NewMockCommentModel(ctrl)
|
|
mockValidate := mocklib.NewMockValidate(ctrl)
|
|
|
|
// 初始化服務上下文
|
|
svcCtx := &svc.ServiceContext{
|
|
CommentModel: mockCommentModel,
|
|
Validate: mockValidate,
|
|
}
|
|
|
|
// 測試數據
|
|
getCommentsReq := &tweeting.GetCommentsReq{
|
|
PostId: "12345",
|
|
PageSize: 10,
|
|
PageIndex: 1,
|
|
}
|
|
|
|
mockComments := []*model.Comment{
|
|
{
|
|
ID: primitive.NewObjectID(),
|
|
PostID: "12345",
|
|
UID: "54321",
|
|
Content: "This is a comment",
|
|
LikeCount: 10,
|
|
DisLikeCount: 2,
|
|
},
|
|
{
|
|
ID: primitive.NewObjectID(),
|
|
PostID: "12345",
|
|
UID: "67890",
|
|
Content: "This is another comment",
|
|
LikeCount: 5,
|
|
DisLikeCount: 1,
|
|
},
|
|
}
|
|
|
|
// 測試數據集
|
|
tests := []struct {
|
|
name string
|
|
input *tweeting.GetCommentsReq
|
|
prepare func()
|
|
expectErr bool
|
|
}{
|
|
{
|
|
name: "成功查詢評論",
|
|
input: getCommentsReq,
|
|
prepare: func() {
|
|
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1)
|
|
mockCommentModel.EXPECT().Find(gomock.Any(), gomock.Any()).Return(mockComments, int64(len(mockComments)), nil).Times(1)
|
|
},
|
|
expectErr: false,
|
|
},
|
|
{
|
|
name: "查詢評論失敗",
|
|
input: getCommentsReq,
|
|
prepare: func() {
|
|
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1)
|
|
mockCommentModel.EXPECT().Find(gomock.Any(), gomock.Any()).Return(nil, int64(0), errors.New("find failed")).Times(1)
|
|
},
|
|
expectErr: true,
|
|
},
|
|
{
|
|
name: "驗證失敗",
|
|
input: getCommentsReq,
|
|
prepare: func() {
|
|
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(errors.New("validation failed")).Times(1)
|
|
},
|
|
expectErr: true,
|
|
},
|
|
}
|
|
|
|
// 執行測試
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
// 設置測試環境
|
|
tt.prepare()
|
|
|
|
// 初始化 GetCommentsLogic
|
|
logic := GetCommentsLogic{
|
|
svcCtx: svcCtx,
|
|
ctx: context.TODO(),
|
|
}
|
|
|
|
// 執行 GetComments
|
|
resp, err := logic.GetComments(tt.input)
|
|
|
|
// 驗證結果
|
|
if tt.expectErr {
|
|
assert.Error(t, err)
|
|
assert.Nil(t, resp)
|
|
} else {
|
|
assert.NoError(t, err)
|
|
assert.NotNil(t, resp)
|
|
assert.Len(t, resp.Comments, len(mockComments))
|
|
}
|
|
})
|
|
}
|
|
}
|