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.


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

package league

import (

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

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

func TestMain(m *testing.M) {
code := m.Run()

func setup() {
// Prepare database. You can get these from env vars if you wish.
adr := "user:pass@tcp("
DB, _ := sql.Open("mysql", adr)

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

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