跳至主要内容

在 Go 專案測試資料庫連線

以下為測試資料庫連線的範例代碼

main_test.go
package db

import (
"database/sql"
"log"
"os"
"testing"
)

const (
dbDriver = "postgres"
dbSource = "postgresql://root:secret@localhost:5432/hr_system?sslmode=disable"
)

var testQueries *Queries
var testDB *sql.DB

func TestMain(m *testing.M) {
var err error

testDB, err = sql.Open(dbDriver, dbSource)
if err != nil {
log.Fatal("Cannot connect to db:", err)
}
// New() 是 sqlc 生成的函式
testQueries = New(testDB)

os.Exit(m.Run())
}

上述代碼執行後若出現下列錯誤訊息,表示專案尚未引用資料庫 driver

Cannot connect to db:sql: unknown driver "postgres" (forgotten import?)

下列連結為資料庫 driver 清單。以 PostgreSQL 為例,可透過清單中的 lib/pq 為專案添加 SQL Driver

SQL Drivers

terminal
$ go get github.com/lib/pq
main_test.go
import _ "github.com/lib/pq"