DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Expectations are not checked if database is not used at all

mathiasringhof opened this issue · comments

The following test will pass even if it shouldn't:

func TestSomething(t *testing.T) {
    db, err := sql.Open("mock", "")
    if err != nil {
        t.Fatalf("Could not open mock database: %v", err)
    }
    sqlmock.ExpectExec("DELETE foo").WillReturnResult(sqlmock.NewResult(1, 1))
    if err = db.Close(); err != nil {
        t.Fatalf("Could not close database: %v", err)
    }
}

If I do something with the database, this will fail as expected:

func TestSomething(t *testing.T) {
    db, err := sql.Open("mock", "")
    if err != nil {
        t.Fatalf("Could not open mock database: %v", err)
    }
    sqlmock.ExpectExec("DELETE foo").WillReturnResult(sqlmock.NewResult(1, 1))
    db.Begin() //db.Exec works as well
    if err = db.Close(); err != nil {
        t.Fatalf("Could not close database: %v", err)
    }
}

Hi, looks like the driver.Close is not triggered. will add this test into suite and check what actions could be applied. thanks for the details

Thanks! Just discovered that a simple db.Ping() works and is a nice workaround.

Have added a method sqlmock.New() which opens a mock connections and pings it. Using it as a shortcut, will save you from this trouble. The issue was that sql driver Close was not triggered, looks like connection is not being opened unless a database is used. There is no direct hook to ping the database otherwise from the driver side. While keeping all backwards compatible, this should handle the case, could not think of something more convenient, if you have any ideas, you are welcome.