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

How to expect a prepared insert ? #71

Closed
ghost opened this issue Mar 17, 2017 · 5 comments
Closed

How to expect a prepared insert ? #71

ghost opened this issue Mar 17, 2017 · 5 comments

Comments

@ghost
Copy link

ghost commented Mar 17, 2017


func TestLogHistory(t *testing.T) {
	var mock sqlmock.Sqlmock
	var err error
	db, mock, err = sqlmock.New()
	if err != nil {
		t.Fatal(err)
	}

	mock.ExpectPrepare("INSERT INTO").ExpectExec().WithArgs("2")

	stmt, err := db.Prepare("INSERT INTO history VALUES(?)")
	if err != nil {
		panic(err)
	}

	if _, err := stmt.Exec("2"); err != nil {
		t.Fatal(err)
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}
--- FAIL: TestLogHistory (0.00s)
	db_test.go:33: exec query 'INSERT INTO history VALUES(?)' with args [2], must return a database/sql/driver.result, but it was not set for expectation *sqlmock.ExpectedExec as ExpectedExec => expecting Exec which:
		  - matches sql: 'INSERT INTO'
		  - is with arguments:
		    0 - 2

I can't figure out how to setup the mock to expect an insert. Any tips ?

@l3pp4rd
Copy link
Member

l3pp4rd commented Mar 17, 2017

Hi, you can look into the tests of sqlmock for more details. the error message says, that you must mock the result Exec should return

func TestLogHistory(t *testing.T) {
	var mock sqlmock.Sqlmock
	var err error
	db, mock, err = sqlmock.New()
	if err != nil {
		t.Fatal(err)
	}

	mock.ExpectPrepare("INSERT INTO").ExpectExec().WithArgs("2").WillReturnResult(sqlmock.NewResult(1, 1))

	stmt, err := db.Prepare("INSERT INTO history VALUES(?)")
	if err != nil {
		panic(err)
	}

	if _, err := stmt.Exec("2"); err != nil {
		t.Fatal(err)
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}

Because it has to produce the result with a number off affected rows and last insert ID if available.

@ghost
Copy link
Author

ghost commented Mar 17, 2017

omg wow, I'm such a doofus, thank you so much

@l3pp4rd
Copy link
Member

l3pp4rd commented Mar 17, 2017

happens for everyone, cheers ;)

@l3pp4rd l3pp4rd closed this as completed Mar 17, 2017
@ivaylopivanov
Copy link

@l3pp4rd I'm not able to use WillReturnRows with ExpectPrepare and I need that in order to make a select query. Is there a workaround?

@ivaylopivanov
Copy link

OK, found it in the tests ExpectQuery

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

2 participants