go20/day06/userapp/models/user_test.go

69 lines
3.1 KiB
Go
Raw Permalink Normal View History

2026-03-08 15:20:41 +08:00
// run package tests: 运行当前包下的所有测试函数 (*_test.go)
// /usr/local/go/bin/go test -test.fullpath=true -timeout 300s -coverprofile=/var/folders/51/dnfr1hzd53x03k3fxnnyd4qc0000gn/T/vscode-golzp26T/go-code-cover userapp/models -v -count=1
// run file tests: 运行当前文件下的所有测试函数(user_test)
2026-03-08 11:01:59 +08:00
package models_test
// models 内部测试(可以测试私有方法)
// models_test 外部测试(只能测试公开方法)
import (
"testing"
"userapp/models"
)
// 采用Log 输出测试结果,方便查看
// run test: 调用的 go test 来执行测试函数 快速测试,自动化的场景
// debug test: 调用 delve(debug工具) 来调试测试函数,单步调试,查看变量的值,适合排查问题 (断点调试)
// 方便 一步一步是每一个函数的执行过程,查看变量的值,适合排查问题
// 打断点:在测试函数的某一行设置断点,当程序执行到该行时会暂停,允许你检查当前的状态和变量的值
func TestUserCheckPasswordHash(t *testing.T) {
user := models.NewUser("张三", "zhangsan@example.com", 25, "password123")
user.ID = 1
2026-03-08 15:20:41 +08:00
user.SetPasswordHash("password123")
// userapp/models/user_test.go:15: true
// 想要看到单元测试的日志, 需要在运行测试时加上 -v 参数,例如 go test -v
// /usr/local/go/bin/go test -test.fullpath=true -timeout 300s -run ^TestUserCheckPasswordHash$ userapp/models -v -count=1
// -v 显示详细的测试输出,包括测试函数的日志信息。
// -count=1 禁止测试结果的缓存,确保每次运行测试时都会执行测试函数,而不是使用之前的测试结果。
// -v -count=1 你们是没有的vscode 设置(go.testFlags):
// "go.testFlags": [
// "-v",
// "-count=1"
// ],
if !user.CheckPasswordHash("password1231") {
// t.Error()
// t.Fatal() 会立即停止测试函数的执行,并标记测试为失败,而 t.Error() 只是记录错误信息,但继续执行测试函数。
t.Fatal("密码验证失败")
}
// fmt.Println()
t.Log("验证成功")
}
func TestUserCheckPasswordHash2(t *testing.T) {
user := models.NewUser("张三", "zhangsan@example.com", 25, "password123")
user.ID = 1
user.SetPasswordHash("password123")
2026-03-08 11:01:59 +08:00
// userapp/models/user_test.go:15: true
// 想要看到单元测试的日志, 需要在运行测试时加上 -v 参数,例如 go test -v
// /usr/local/go/bin/go test -test.fullpath=true -timeout 300s -run ^TestUserCheckPasswordHash$ userapp/models -v -count=1
// -v 显示详细的测试输出,包括测试函数的日志信息。
// -count=1 禁止测试结果的缓存,确保每次运行测试时都会执行测试函数,而不是使用之前的测试结果。
// -v -count=1 你们是没有的vscode 设置(go.testFlags):
// "go.testFlags": [
// "-v",
// "-count=1"
// ],
if !user.CheckPasswordHash("password1231") {
// t.Error()
// t.Fatal() 会立即停止测试函数的执行,并标记测试为失败,而 t.Error() 只是记录错误信息,但继续执行测试函数。
t.Fatal("密码验证失败")
}
t.Log("验证成功")
}