82 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			Go
		
	
	
	
		
		
			
		
	
	
			82 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			Go
		
	
	
	
|  | package postservicelogic | ||
|  | 
 | ||
|  | import ( | ||
|  | 	"app-cloudep-tweeting-service/gen_result/pb/tweeting" | ||
|  | 	mockmodel "app-cloudep-tweeting-service/internal/mock/model" | ||
|  | 	"app-cloudep-tweeting-service/internal/svc" | ||
|  | 	"context" | ||
|  | 	"errors" | ||
|  | 	"testing" | ||
|  | 
 | ||
|  | 	"github.com/stretchr/testify/assert" | ||
|  | 	"go.uber.org/mock/gomock" | ||
|  | ) | ||
|  | 
 | ||
|  | func TestDeletePost(t *testing.T) { | ||
|  | 	ctrl := gomock.NewController(t) | ||
|  | 	defer ctrl.Finish() | ||
|  | 
 | ||
|  | 	// 初始化 mock 依賴
 | ||
|  | 	mockPostModel := mockmodel.NewMockPostModel(ctrl) | ||
|  | 
 | ||
|  | 	// 初始化服務上下文
 | ||
|  | 	svcCtx := &svc.ServiceContext{ | ||
|  | 		PostModel: mockPostModel, | ||
|  | 	} | ||
|  | 
 | ||
|  | 	// 測試數據集
 | ||
|  | 	tests := []struct { | ||
|  | 		name      string | ||
|  | 		input     *tweeting.DeletePostsReq | ||
|  | 		prepare   func() | ||
|  | 		expectErr bool | ||
|  | 	}{ | ||
|  | 		{ | ||
|  | 			name: "成功刪除貼文", | ||
|  | 			input: &tweeting.DeletePostsReq{ | ||
|  | 				PostId: []string{"12345", "67890"}, | ||
|  | 			}, | ||
|  | 			prepare: func() { | ||
|  | 				// 模擬 DeleteMany 成功
 | ||
|  | 				mockPostModel.EXPECT().DeleteMany(gomock.Any(), "12345", "67890").Return(int64(2), nil).Times(1) | ||
|  | 			}, | ||
|  | 			expectErr: false, | ||
|  | 		}, | ||
|  | 		{ | ||
|  | 			name: "刪除貼文失敗", | ||
|  | 			input: &tweeting.DeletePostsReq{ | ||
|  | 				PostId: []string{"12345", "67890"}, | ||
|  | 			}, | ||
|  | 			prepare: func() { | ||
|  | 				// 模擬 DeleteMany 失敗
 | ||
|  | 				mockPostModel.EXPECT().DeleteMany(gomock.Any(), "12345", "67890").Return(int64(0), errors.New("delete failed")).Times(1) | ||
|  | 			}, | ||
|  | 			expectErr: true, | ||
|  | 		}, | ||
|  | 	} | ||
|  | 
 | ||
|  | 	// 執行測試
 | ||
|  | 	for _, tt := range tests { | ||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||
|  | 			// 設置測試環境
 | ||
|  | 			tt.prepare() | ||
|  | 
 | ||
|  | 			// 初始化 DeletePostLogic
 | ||
|  | 			logic := DeletePostLogic{ | ||
|  | 				svcCtx: svcCtx, | ||
|  | 				ctx:    context.TODO(), | ||
|  | 			} | ||
|  | 
 | ||
|  | 			// 執行 DeletePost
 | ||
|  | 			_, err := logic.DeletePost(tt.input) | ||
|  | 
 | ||
|  | 			// 驗證結果
 | ||
|  | 			if tt.expectErr { | ||
|  | 				assert.Error(t, err) | ||
|  | 			} else { | ||
|  | 				assert.NoError(t, err) | ||
|  | 			} | ||
|  | 		}) | ||
|  | 	} | ||
|  | } |