修改单测--目前单测全过
This commit is contained in:
@@ -98,15 +98,19 @@ func TestCreateUser(t *testing.T) {
|
|||||||
},
|
},
|
||||||
mockRepoSetup: func(m *MockUserRepository) {
|
mockRepoSetup: func(m *MockUserRepository) {
|
||||||
// 模拟 Create 成功
|
// 模拟 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 不会被调用,因此这里不需要设置其期望
|
// 在成功创建用户的路径下,FindByUsername 不会被调用,因此这里不需要设置其期望
|
||||||
},
|
},
|
||||||
expectedResponse: map[string]interface{}{
|
expectedResponse: map[string]interface{}{
|
||||||
"code": float64(http.StatusOK),
|
"code": float64(http.StatusCreated), // 修改这里:从 http.StatusOK 改为 http.StatusCreated
|
||||||
"message": "用户创建成功",
|
"message": "用户创建成功",
|
||||||
"data": map[string]interface{}{
|
"data": map[string]interface{}{
|
||||||
"username": "testuser",
|
"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"])
|
assert.Equal(t, tt.expectedResponse["code"], responseBody["code"])
|
||||||
|
|
||||||
// 断言响应内容 (除了 code 字段)
|
// 断言响应内容 (除了 code 字段)
|
||||||
// 对于成功的创建,ID 是动态的,需要特殊处理
|
if tt.expectedResponse["code"] == float64(http.StatusCreated) { // 修改这里:从 http.StatusOK 改为 http.StatusCreated
|
||||||
if tt.expectedResponse["code"] == float64(http.StatusOK) {
|
// 确保 data 字段存在且是 map[string]interface{} 类型
|
||||||
assert.NotNil(t, responseBody["data"].(map[string]interface{})["id"])
|
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 字段以便进行通用断言
|
// 移除 ID 字段以便进行通用断言
|
||||||
delete(responseBody["data"].(map[string]interface{}), "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 字段以便进行通用断言
|
// 移除 code 字段以便进行通用断言
|
||||||
delete(responseBody, "code")
|
delete(responseBody, "code")
|
||||||
|
|||||||
Reference in New Issue
Block a user