go-sqlmock icon indicating copy to clipboard operation
go-sqlmock copied to clipboard

mocking for gorm failed

Open davidxiao opened this issue 4 years ago • 3 comments

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)
        if err != nil {
		t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
	}
	gDB.LogMode(true)
	defer db.Close()
        // mock.MatchExpectationsInOrder(false)// adding this line doesn't help,similar error
	mock.ExpectBegin()
	mock.ExpectExec("INSERT 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)
	}
}

davidxiao avatar Apr 05 '20 12:04 davidxiao

many people are using gorm, I'm sure you are doing something wrong. you do not even check the errors. opening a gorm db may give you an error

l3pp4rd avatar Apr 08 '20 05:04 l3pp4rd

source code was simplified for demo, but added it to avoid confusion It seems related to transaction according to error message? that's why create the ticket, but not so sure.

davidxiao avatar Apr 08 '20 12:04 davidxiao

`call to database transaction Begin, was not expected` Have you tried to remove `mock.ExpectBegin()` and `mock.ExpectCommit()`?

I have the same error as you, but mine is an update query. Cannot figure out which part goes wrong ;)

You can try add

tx := Db.Begin()
if tx.Error != nil {
	return tx.Error
}

and

return tx.Commit().Error

To your recordStats transaction

ryougi-shiky avatar Dec 21 '23 13:12 ryougi-shiky