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

125 lines
3.0 KiB
Go
Raw Permalink Normal View History

package commentservicelogic
import (
"app-cloudep-tweeting-service/gen_result/pb/tweeting"
mocklib "app-cloudep-tweeting-service/internal/mock/lib"
mockmodel "app-cloudep-tweeting-service/internal/mock/model"
"app-cloudep-tweeting-service/internal/svc"
"context"
"errors"
"testing"
"github.com/stretchr/testify/assert"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.uber.org/mock/gomock"
"google.golang.org/protobuf/proto"
)
func TestUpdateComment(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,
}
// 測試數據
commentID := primitive.NewObjectID().Hex()
updateCommentReq := &tweeting.UpdateCommentReq{
CommentId: commentID,
Content: "Updated content",
LikeCount: proto.Int64(5),
DislikeCount: proto.Int64(2),
}
// 測試數據集
tests := []struct {
name string
input *tweeting.UpdateCommentReq
prepare func()
expectErr bool
}{
{
name: "成功更新評論",
input: updateCommentReq,
prepare: func() {
// 模擬 Validate 成功
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1)
// 模擬 UpdateOptional 成功
mockCommentModel.EXPECT().UpdateOptional(gomock.Any(), gomock.Any()).Return(&mongo.UpdateResult{
ModifiedCount: 1,
}, nil).Times(1)
},
expectErr: false,
},
{
name: "驗證失敗",
input: updateCommentReq,
prepare: func() {
// 模擬 Validate 失敗
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(errors.New("validation failed")).Times(1)
},
expectErr: true,
},
{
name: "更新評論失敗",
input: updateCommentReq,
prepare: func() {
// 模擬 Validate 成功
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1)
// 模擬 UpdateOptional 失敗
mockCommentModel.EXPECT().UpdateOptional(gomock.Any(), gomock.Any()).Return(
&mongo.UpdateResult{
ModifiedCount: 0,
}, errors.New("update failed")).Times(1)
},
expectErr: true,
},
{
name: "無效的評論ID",
input: &tweeting.UpdateCommentReq{
CommentId: "invalid_id",
Content: "Updated content",
},
prepare: func() {
// 模擬 Validate 成功
mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1)
},
expectErr: true,
},
}
// 執行測試
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 設置測試環境
tt.prepare()
// 初始化 UpdateCommentLogic
logic := UpdateCommentLogic{
svcCtx: svcCtx,
ctx: context.TODO(),
}
// 執行 UpdateComment
resp, err := logic.UpdateComment(tt.input)
// 驗證結果
if tt.expectErr {
assert.Error(t, err)
assert.Nil(t, resp)
} else {
assert.NoError(t, err)
assert.NotNil(t, resp)
}
})
}
}