> func connectToDB(t *testing.T) *postgres.DB {
>     t.Helper()
>     // set up the connection, using t.Fatalf if an error occurs
>     return conn
> }
>
> func UserTest(t *testing.T) {
>     db := connectToDB(t)
> }
>

Yeah, that's a good way.

And if you want to avoid re-connecting to the db every test, you can use a 
top-level test function for the "suite", and sub-tests with t.Run() for the 
individual tests, with the sub-tests closing over the db variable. Like so:

func TestDatabaseThings(t *testing.T) {
    db := connectToDB(t)

    t.Run("Foo", func (t *testing.T) {
        fmt.Println(db, "test foo stuff") // use "db" and test stuff
    })

    t.Run("Bar", func (t *testing.T) {
        fmt.Println(db, "test bar stuff") // use "db" and test stuff
    })
}

-Ben

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/ba07e1df-e62a-4461-8f62-29b45255b7acn%40googlegroups.com.

Reply via email to