So far I never needed to mock a database in Golang unit tests so I just worked with an instance instead. This examples show how it can be done. It is pretty fast so I wouldn't bother with mocking it.


Helper


Assume that you have this helper to automatically setup and destroy the database instance for your test.


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")
}

From now on, you can use DB variable in test cases that depend on a database instance.