sqlmock database is closed issue

382 Views Asked by At

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...

1

There are 1 best solutions below

0
On

I found a way to do it in test

db, mock, dbError := sqlmock.New()
defer db.Close()
db2, mock2, dbError2 := sqlmock.New()
defer db2.Close()
assert.Nil(t, dbError)
assert.Nil(t, dbError2)
setUpDB = func() *sql.DB {
    if mock.ExpectationsWereMet() == nil {
        return db2
    }
    return db
}