package postservicelogic import ( "app-cloudep-tweeting-service/gen_result/pb/tweeting" "app-cloudep-tweeting-service/internal/svc" "context" "errors" "testing" mocklib "app-cloudep-tweeting-service/internal/mock/lib" mockmodel "app-cloudep-tweeting-service/internal/mock/model" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" ) func TestCreatePost(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.NewPostReq prepare func() expectErr bool }{ { name: "成功創建貼文", input: &tweeting.NewPostReq{ Uid: "12345", Content: "Test content", IsAd: false, Tags: []string{"tag1", "tag2"}, Media: []*tweeting.Media{ { Url: "http://example.com/image.png", Type: "image", }, }, }, prepare: func() { mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1) mockPostModel.EXPECT().Insert(gomock.Any(), gomock.Any()).Return(nil).Times(1) }, expectErr: false, }, { name: "驗證失敗", input: &tweeting.NewPostReq{ Uid: "", Content: "", }, prepare: func() { mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(errors.New("validation failed")).Times(1) }, expectErr: true, }, { name: "插入貼文失敗", input: &tweeting.NewPostReq{ Uid: "12345", Content: "Test content", IsAd: false, }, prepare: func() { mockValidate.EXPECT().ValidateAll(gomock.Any()).Return(nil).Times(1) mockPostModel.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() // 初始化 CreatePostLogic logic := CreatePostLogic{ svcCtx: svcCtx, ctx: context.TODO(), } // 執行 CreatePost _, err := logic.CreatePost(tt.input) // 驗證結果 if tt.expectErr { assert.Error(t, err) } else { assert.NoError(t, err) } }) } }