package handler import ( "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/api/handlers" "github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/common" "github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/services" ) type MockVocabularyService struct { mock.Mock } // 显式实现 VocabularyServiceInterface 接口 var _ interfaces.VocabularyServiceInterface = (*MockVocabularyService)(nil) func (m *MockVocabularyService) GetDailyStats(userID string) (map[string]interface{}, error) { args := m.Called(userID) return args.Get(0).(map[string]interface{}), args.Error(1) } func TestGetDailyVocabularyStats(t *testing.T) { // 初始化 Gin 引擎 gin.SetMode(gin.TestMode) r := gin.Default() // 创建 Mock 服务 mockService := new(MockVocabularyService) mockService.On("GetDailyStats", "test_user").Return(map[string]interface{}{ "wordsLearned": 10, "studyTimeMinutes": 30, }, nil) mockService.On("GetDailyStats", "").Return(nil, common.NewBusinessError(400, "用户ID不能为空")) // 创建处理器 h := handlers.NewVocabularyHandler(mockService, nil) r.GET("/api/vocabulary/daily", h.GetDailyVocabularyStats) // 测试成功情况 req, _ := http.NewRequest(http.MethodGet, "/api/vocabulary/daily?user_id=test_user", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "wordsLearned") assert.Contains(t, w.Body.String(), "studyTimeMinutes") // 测试缺少用户ID req, _ = http.NewRequest(http.MethodGet, "/api/vocabulary/daily", nil) w = httptest.NewRecorder() r.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, w.Body.String(), "用户ID不能为空") }