package postservicelogic 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" "go.mongodb.org/mongo-driver/mongo" "google.golang.org/protobuf/proto" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" "testing" ) func TestUpdatePost(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() // 初始化 mock 依賴 mockPostModel := mockmodel.NewMockPostModel(ctrl) mockValidate := mocklib.NewMockValidate(ctrl) // 初始化服務上下文 svcCtx := &svc.ServiceContext{ PostModel: mockPostModel, Validate: mockValidate, } // 測試數據集 tests := []struct { name string input *tweeting.UpdatePostReq prepare func() expectErr bool }{ { name: "成功更新貼文", input: &tweeting.UpdatePostReq{ PostId: "66cfdc1d6f8fe7eac1e52523", Content: proto.String("Updated content"), Tags: []string{"tag1", "tag2"}, Media: []*tweeting.Media{ { Url: "http://example.com/image.png", Type: "image", }, }, LikeCount: proto.Int64(10), DislikeCount: proto.Int64(2), }, prepare: func() { // 模擬 Validate 成功 mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1) // 模擬 UpdateOptional 成功 mockPostModel.EXPECT().UpdateOptional(gomock.Any(), gomock.Any()).Return(&mongo.UpdateResult{ ModifiedCount: 1, }, nil).Times(1) }, expectErr: false, }, { name: "驗證失敗", input: &tweeting.UpdatePostReq{ PostId: "", }, prepare: func() { // 模擬 Validate 失敗 mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(errors.New("validation failed")).Times(1) }, expectErr: true, }, { name: "更新貼文失敗", input: &tweeting.UpdatePostReq{ PostId: "66cfdc1d6f8fe7eac1e52523", Content: proto.String("Updated content"), }, prepare: func() { // 模擬 Validate 成功 mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1) // 模擬 UpdateOptional 失敗 mockPostModel.EXPECT().UpdateOptional(gomock.Any(), gomock.Any()).Return(&mongo.UpdateResult{ ModifiedCount: 0, }, errors.New("update failed")).Times(1) }, expectErr: true, }, } // 執行測試 for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // 設置測試環境 tt.prepare() // 初始化 UpdatePostLogic logic := UpdatePostLogic{ svcCtx: svcCtx, ctx: context.TODO(), } // 執行 UpdatePost _, err := logic.UpdatePost(tt.input) // 驗證結果 if tt.expectErr { assert.Error(t, err) } else { assert.NoError(t, err) } }) } }