DATA-DOG / go-sqlmock

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

mocking with gorm failed #220

Closed davidxiao closed 4 years ago

davidxiao commented 4 years ago

What version of Go are you using (go version)? go version go1.14 darwin/amd64

github.com/DATA-DOG/go-sqlmock v1.4.1

github.com/jinzhu/gorm v1.9.12

Which database and its version are you using? postgres 10.11

description? Basically it's very simple from readme of https://github.com/DATA-DOG/go-sqlmock, with little change, I tried to mock in project, but got the below issue, and so copied the sample from sqlmock repo, and tried, and got the same, Can someone pls help? didn't use gorm and sqlmock before. thanks very much,

call to database transaction Begin, was not expected, next expectation is: ExpectedExec => expecting Exec or ExecContext which matches sql: 'UPDATE products' is without arguments should return Result having: LastInsertId: 1 RowsAffected: 1 Please provide a complete runnable program to reproduce your issue. IMPORTANT package main

import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" )

type product struct { Views int64 } type product_viewer struct { UserId int64 ProductId int64 }

func recordStats(db gorm.DB, userID, productID int64) (err error) { return db.Transaction(func(tx gorm.DB) error { p := product{ Views: 10, } pv := product_viewer{ UserId: 111, ProductId: 222, } if err = db.Save(&p).Error; err != nil { return nil } return db.Create(&pv).Error }) }

func main() { db, err := gorm.Open("postgres", "user=postgres password=postgres dbname=demo sslmode=disable") if err != nil { panic(err) } defer db.Close()

if err = recordStats(db, 1 /*some user id*/, 5 /*some product id*/); err != nil {
    panic(err)
}

} package main

import ( "testing"

"github.com/DATA-DOG/go-sqlmock"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"

)

// a successful case func TestWithGorm(t *testing.T) { db, mock, err := sqlmock.New() if err != nil { t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) } gDB, err := gorm.Open("postgres", db) gDB.LogMode(true) defer db.Close()

mock.ExpectBegin()
mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()

// now we execute our method
if err = recordStats(gDB, 2, 3); err != nil {
    t.Errorf("error was not expected while updating stats: %s", err)
}

// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
    t.Errorf("there were unfulfilled expectations: %s", err)
}

}