2014-08-14 20:35:18 +03:00
|
|
|
package sqlmock
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
2015-07-17 12:14:30 +02:00
|
|
|
// used for examples
|
2015-08-28 10:06:14 +02:00
|
|
|
var mock = &sqlmock{}
|
2015-07-17 12:14:30 +02:00
|
|
|
|
|
|
|
func ExampleNewErrorResult() {
|
2015-07-22 15:17:35 +02:00
|
|
|
db, mock, _ := New()
|
2015-07-17 12:14:30 +02:00
|
|
|
result := NewErrorResult(fmt.Errorf("some error"))
|
|
|
|
mock.ExpectExec("^INSERT (.+)").WillReturnResult(result)
|
2015-07-22 15:17:35 +02:00
|
|
|
res, _ := db.Exec("INSERT something")
|
|
|
|
_, err := res.LastInsertId()
|
|
|
|
fmt.Println(err)
|
|
|
|
// Output: some error
|
2015-07-17 12:14:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func ExampleNewResult() {
|
|
|
|
var lastInsertID, affected int64
|
|
|
|
result := NewResult(lastInsertID, affected)
|
|
|
|
mock.ExpectExec("^INSERT (.+)").WillReturnResult(result)
|
2015-07-22 15:17:35 +02:00
|
|
|
fmt.Println(mock.ExpectationsWereMet())
|
2017-04-26 08:56:02 +02:00
|
|
|
// Output: there is a remaining expectation which was not matched: ExpectedExec => expecting Exec or ExecContext which:
|
2015-08-26 15:59:28 +02:00
|
|
|
// - matches sql: '^INSERT (.+)'
|
|
|
|
// - is without arguments
|
|
|
|
// - should return Result having:
|
|
|
|
// LastInsertId: 0
|
|
|
|
// RowsAffected: 0
|
2015-07-17 12:14:30 +02:00
|
|
|
}
|
|
|
|
|
2014-08-14 20:35:18 +03:00
|
|
|
func TestShouldReturnValidSqlDriverResult(t *testing.T) {
|
|
|
|
result := NewResult(1, 2)
|
|
|
|
id, err := result.LastInsertId()
|
|
|
|
if 1 != id {
|
2019-02-27 21:44:03 +02:00
|
|
|
t.Errorf("expected last insert id to be 1, but got: %d", id)
|
2014-08-14 20:35:18 +03:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("expected no error, but got: %s", err)
|
|
|
|
}
|
|
|
|
affected, err := result.RowsAffected()
|
|
|
|
if 2 != affected {
|
2019-02-27 21:44:03 +02:00
|
|
|
t.Errorf("expected affected rows to be 2, but got: %d", affected)
|
2014-08-14 20:35:18 +03:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("expected no error, but got: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-27 21:44:03 +02:00
|
|
|
func TestShouldReturnErrorSqlDriverResult(t *testing.T) {
|
2014-08-14 20:35:18 +03:00
|
|
|
result := NewErrorResult(fmt.Errorf("some error"))
|
|
|
|
_, err := result.LastInsertId()
|
|
|
|
if err == nil {
|
|
|
|
t.Error("expected error, but got none")
|
|
|
|
}
|
|
|
|
_, err = result.RowsAffected()
|
|
|
|
if err == nil {
|
|
|
|
t.Error("expected error, but got none")
|
|
|
|
}
|
|
|
|
}
|