Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mocking for gorm failed #221

Open
davidxiao opened this issue Apr 5, 2020 · 3 comments
Open

mocking for gorm failed #221

davidxiao opened this issue Apr 5, 2020 · 3 comments

Comments

@davidxiao
Copy link

davidxiao commented Apr 5, 2020

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)
	}
}
@l3pp4rd
Copy link
Member

l3pp4rd commented Apr 8, 2020

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

@davidxiao
Copy link
Author

davidxiao commented Apr 8, 2020

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.

@ryougi-shiky
Copy link

ryougi-shiky commented Dec 21, 2023

`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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants