在Golang单元测试中与数据库互动的实例

125 阅读1分钟

到目前为止,我从来不需要在Golang单元测试中模拟数据库,所以我只是用一个实例来代替。这个例子展示了它是如何做到的。它是相当快的,所以我不会费力地去模拟它。

帮助器

假设你有这个助手来为你的测试自动设置和销毁数据库实例:

package league

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

// -----------------------------------------------------------------------------

// Inject this to where it is needed.
var DB *sql.DB

func TestMain(m *testing.M) {
	setup()
	code := m.Run()
	teardown()
	os.Exit(code)
}

func setup() {
	// Prepare database. You can get these from env vars if you wish.
	adr := "user:pass@tcp(0.0.0.0:3306)/sport?charset=utf8mb4&collation=utf8mb4_unicode_ci"
	DB, _ := sql.Open("mysql", adr)
	DB.SetMaxIdleConns(5)

	// Prepare some more dependencies here if you need.

	fmt.Printf("\033[1;36m%s\033[0m", "> Setup completed\n")
}

func teardown() {
	// Close the database instance.
	_ = DB.Close()

	// Destroy other dependencies here if you created.

	fmt.Printf("\033[1;36m%s\033[0m", "> Teardown completed")
	fmt.Printf("\n")
}

从现在开始,你可以在依赖数据库实例的测试案例中使用DB 变量。