执行了go test ./... 以后出现下面的bug
Go
? practic_todolist/cmd/todo [no test files]
? practic_todolist/internal/config [no test files]
2026/04/15 22:44:19 C:/Users/gaoru/Desktop/practic_todolist/internal/handler/todo_handler_test.go:34
[error] failed to initialize database, got error Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub
--- FAIL: TestTodoHandlerEndpoints (0.01s)
todo_handler_test.go:55: open test database: Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub
FAIL
FAIL practic_todolist/internal/handler 1.211s
? practic_todolist/internal/model [no test files]
? practic_todolist/internal/repository [no test files]
ok practic_todolist/internal/service 0.596s
? practic_todolist/pkg/database [no test files]
FAIL
解决办法:
我的测试代码在连接 SQLite 时失败了,因为当前Go环境是CGO_ENABLED=0,而我现在用的 SQLite 驱动需要CGO。
更直白一点:
项目里的service测试能过,是因为它用了mock仓库,不需要真连数据库,handler集成测试会真的打开 SQLite 内存库,我现在的 SQLite 驱动底层依赖 go-sqlite3,go-sqlite3 在Windows 上通常需要:CGO_ENABLED=1,本机有 C 编译器,但我当前测试是用禁用 CGO 的方式编译出来的,所以数据库初始化直接失败了
报错里这句就是核心:
Binary was compiled with 'CGO_ENABLED=0'
go-sqlite3 requires cgo to work
这意味着目前不是我的业务代码逻辑错了,而是运行环境和SQLite驱动不匹配
有两种解决方案:
第一种是开启 CGO,并安装 C 编译环境
适合继续使用当前 gorm.io/driver/sqlite
先检查
Go
go env CGO_ENABLED
gcc --version
如果 CGO_ENABLED 是 0,可以尝试:
Go
go env -w CGO_ENABLED=1
但在 Windows 上,通常还要安装 gcc,否则还是不行。
第二种则就是把项目改成"不依赖 CGO"的纯 Go SQLite 驱动。