app-cloudep-tweeting-service/internal/logic/commentservice/new_comment_logic_test.go

125 lines
3.2 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 TestNewComment(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// 初始化 mock 依賴
mockPostModel := mockmodel.NewMockPostModel(ctrl)
mockCommentModel := mockmodel.NewMockCommentModel(ctrl)
mockValidate := mocklib.NewMockValidate(ctrl)
// 初始化服務上下文
svcCtx := &svc.ServiceContext{
PostModel: mockPostModel,
CommentModel: mockCommentModel,
Validate: mockValidate,
}
// 測試數據
postID := primitive.NewObjectID().Hex()
commentReq := &tweeting.CommentPostReq{
Uid: "12345",
Content: "This is a comment",
PostId: postID,
}
// 測試數據集
tests := []struct {
name string
input *tweeting.CommentPostReq
prepare func()
expectErr bool
}{
{
name: "成功發表評論",
input: commentReq,
prepare: func() {
// 模擬 Validate 成功
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1)
// 模擬 FindOne 成功找到文章
mockPostModel.EXPECT().FindOne(gomock.Any(), postID).Return(&model.Post{}, nil).Times(1)
// 模擬 Insert 成功
mockCommentModel.EXPECT().Insert(gomock.Any(), gomock.Any()).Return(nil).Times(1)
},
expectErr: false,
},
{
name: "驗證失敗",
input: commentReq,
prepare: func() {
// 模擬 Validate 失敗
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(errors.New("validation failed")).Times(1)
},
expectErr: true,
},
{
name: "文章不存在",
input: commentReq,
prepare: func() {
// 模擬 Validate 成功
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1)
// 模擬 FindOne 找不到文章
mockPostModel.EXPECT().FindOne(gomock.Any(), postID).Return(nil, model.ErrNotFound).Times(1)
},
expectErr: true,
},
{
name: "插入評論失敗",
input: commentReq,
prepare: func() {
// 模擬 Validate 成功
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1)
// 模擬 FindOne 成功找到文章
mockPostModel.EXPECT().FindOne(gomock.Any(), postID).Return(&model.Post{}, nil).Times(1)
// 模擬 Insert 失敗
mockCommentModel.EXPECT().Insert(gomock.Any(), gomock.Any()).Return(errors.New("insert failed")).Times(1)
},
expectErr: true,
},
}
// 執行測試
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 設置測試環境
tt.prepare()
// 初始化 NewCommentLogic
logic := NewCommentLogic{
svcCtx: svcCtx,
ctx: context.TODO(),
}
// 執行 NewComment
resp, err := logic.NewComment(tt.input)
// 驗證結果
if tt.expectErr {
assert.Error(t, err)
assert.Nil(t, resp)
} else {
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.NotEmpty(t, resp.CommentId)
}
})
}
}