DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.06k stars 408 forks source link

False passing of ExpectExec #143

Closed willis7 closed 5 years ago

willis7 commented 6 years ago

This could be a fundamental misunderstanding of the framework, or a real bug.

Code under test

type repository struct {
    db *sqlx.DB
}

func (r repository) Create(environment Environment) error {
    tx := r.db.MustBegin()
    tx.NamedExec("INSERT INTO environment (name) VALUES (:name)", environment)
    return tx.Commit()
}

Test

func TestRepository_Create(t *testing.T) {
    mockDB, mock, err := sqlmock.New()
        defer mockDB.Close()
    db := sqlx.NewDb(mockDB, "sqlmock")

    repo := repository{
        db: db,
    }

    mock.ExpectBegin()
    mock.ExpectExec("garbage").WithArgs("test store")
    mock.ExpectCommit()

    repo.Create(Environment{Name: "foo"})
}

I would expect mock.ExpectExec("garbage") to fail, but it passes every time.

l3pp4rd commented 6 years ago

Hi, in go errors need to be checked, read the examples and look at the test files, in this case NamedExec fails with an error because the sql.Result is not mocked and you do not check errors. read examples to understand the library you are using before asking any questions

willis7 commented 6 years ago

I removed the errors for brevity. I have also read the examples and they are all too simple to be helpful here. There are no examples with sqlx, which is to be expected, and so questioning here seems like the most obvious course of action.

willis7 commented 5 years ago

This was a lack of understanding on my part. Closing