My problem is that the connection to db is closed when I open it twice in the same func.
This is the code example that I need to test:
var openDB := func() *sql.DB {
db, _ := sql.Open()
return db
}
func doSomeQuery(id string) bool {
var exists bool
db := openDB()
defer db.Close()
db.QueryRow("... some query", id).Scan(&exists)
return exists
}
func toTest() bool, bool {
exists1 := doSomeQuery("run1")
exists2 := doSomeQuery("run2")
return exists1, exists2
}
This is my test example:
func TestSomeTestName(t *testing.T) {
db, mock, _ sqlmock.New()
defer db.Close()
var openDB := func() *sql.DB {
return db
}
mock.ExpectQuery(some query for run1...)
mock.ExpectQuery(some query for run2...)
res1, res2 := toTest()
assert.True(t, res1)
assert.True(t, res2)
}
No the problem is that the first query works fine but on the second one I get error: database is closed
Is there a way to avoid closing DB after the first run in test, without changing the code? The code works in production, I just need to test it somehow...
I found a way to do it in test