DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.05k stars 406 forks source link

ExpectationsWereMet not working #217

Closed lightyear15 closed 4 years ago

lightyear15 commented 4 years ago
package main

import (
    "fmt"
    "github.com/DATA-DOG/go-sqlmock"
)

func main() {
    db, mock, err := sqlmock.New()
    if err != nil {
        fmt.Println("error creating mock database")
        return
    }

    rows := sqlmock.NewRows([]string{"id", "status"}).AddRow(1, 1)
    customQuery := ("SELECT * FROM db WHERE id = 10")
    mock.ExpectQuery(customQuery).WillReturnRows(rows)

    var c1, c2 int
    err = db.QueryRow(customQuery).Scan(&c1, &c2)
    if err != nil {
        fmt.Println("error:", err)
    }

    if err := mock.ExpectationsWereMet(); err != nil {
        fmt.Printf("mock expectation fail: %s", err)
    }
}

outputs:

error: Query: could not match actual sql: "SELECT * FROM db WHERE id = 10" with expected regexp "SELECT * FROM db WHERE id = 10"
mock expectation fail: there is a remaining expectation which was not matched: ExpectedQuery => expecting Query, QueryContext or QueryRow which:
  - matches sql: 'SELECT * FROM db WHERE id = 10'
  - is without arguments
  - should return rows:
    row 0 - [1 1]

While:

package main

import (
    "errors"
    "fmt"

    "github.com/DATA-DOG/go-sqlmock"
)

func main() {
    db, mock, err := sqlmock.New()
    if err != nil {
        fmt.Println("error creating mock database")
        return
    }
    customQuery := ("SELECT * FROM db WHERE id = 10")
    mock.ExpectQuery(customQuery).WillReturnError(errors.New("error"))
    _, err = db.Query(customQuery)
    if err := mock.ExpectationsWereMet(); err != nil {
        fmt.Printf("mock expectation fail: %s", err)
    }
}

outputs:

mock expectation fail: there is a remaining expectation which was not matched: ExpectedQuery => expecting Query, QueryContext or QueryRow which:
  - matches sql: 'SELECT * FROM db WHERE id = 10'
  - is without arguments
  - should return error: error

running on

l3pp4rd commented 4 years ago

You should read the api docs. It uses regexp as an argument by default, not a plain string. So the ‘*’ and other regexp symbols has to be escaped

lightyear15 commented 4 years ago

You should read the api docs. It uses regexp as an argument by default, not a plain string. So the ‘*’ and other regexp symbols has to be escaped

Thanks a lot, sorry for the noise