From 0884e229feba8134fc63ce317a28837bd8e00248 Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Fri, 12 Sep 2025 20:28:57 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8D=95=E6=B5=8B--=E7=9B=AE?= =?UTF-8?q?=E5=89=8D=E5=8D=95=E6=B5=8B=E5=85=A8=E8=BF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/user/user_controller_test.go | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/internal/app/controller/user/user_controller_test.go b/internal/app/controller/user/user_controller_test.go index 79047d4..2f165bc 100644 --- a/internal/app/controller/user/user_controller_test.go +++ b/internal/app/controller/user/user_controller_test.go @@ -98,15 +98,19 @@ func TestCreateUser(t *testing.T) { }, mockRepoSetup: func(m *MockUserRepository) { // 模拟 Create 成功 - m.On("Create", mock.AnythingOfType("*models.User")).Return(nil).Once() + m.On("Create", mock.AnythingOfType("*models.User")).Return(nil).Run(func(args mock.Arguments) { + // 模拟数据库自动填充 ID + userArg := args.Get(0).(*models.User) + userArg.ID = 1 // 设置一个非零的 ID + }).Once() // 在成功创建用户的路径下,FindByUsername 不会被调用,因此这里不需要设置其期望 }, expectedResponse: map[string]interface{}{ - "code": float64(http.StatusOK), + "code": float64(http.StatusCreated), // 修改这里:从 http.StatusOK 改为 http.StatusCreated "message": "用户创建成功", "data": map[string]interface{}{ "username": "testuser", - "id": mock.Anything, // ID 是动态生成的,我们只检查存在 + // "id": mock.Anything, // 移除这里的 id,在断言时单独检查 }, }, }, @@ -210,12 +214,21 @@ func TestCreateUser(t *testing.T) { assert.Equal(t, tt.expectedResponse["code"], responseBody["code"]) // 断言响应内容 (除了 code 字段) - // 对于成功的创建,ID 是动态的,需要特殊处理 - if tt.expectedResponse["code"] == float64(http.StatusOK) { - assert.NotNil(t, responseBody["data"].(map[string]interface{})["id"]) + if tt.expectedResponse["code"] == float64(http.StatusCreated) { // 修改这里:从 http.StatusOK 改为 http.StatusCreated + // 确保 data 字段存在且是 map[string]interface{} 类型 + data, ok := responseBody["data"].(map[string]interface{}) + assert.True(t, ok, "响应体中的 data 字段应为 map[string]interface{}") + // 确保 id 字段存在且不为零 + id, idOk := data["id"].(float64) + assert.True(t, idOk, "响应体中的 data.id 字段应为 float64 类型") + assert.NotEqual(t, float64(0), id, "响应体中的 data.id 不应为零") + // 移除 ID 字段以便进行通用断言 delete(responseBody["data"].(map[string]interface{}), "id") - delete(tt.expectedResponse["data"].(map[string]interface{}), "id") + // 移除 expectedResponse 中的 id 字段,因为我们已经单独验证了 + if expectedData, ok := tt.expectedResponse["data"].(map[string]interface{}); ok { + delete(expectedData, "id") + } } // 移除 code 字段以便进行通用断言 delete(responseBody, "code")