5

我将Gorm与 postgresql 驱动程序一起使用。我尝试使用go-sqlmock模拟数据库插入:

type Test struct {
    FirstName string `json:"first_name"`
}

func (db *DB) CreateTest() (*Test, error) {
    test := Test{"c"}
    if result := db.Create(&test); result.Error != nil {
        return nil, result.Error
    }

    return &test, nil
}


func TestCreateUser(t *testing.T) {
    _, mock, _ := sqlmock.NewWithDSN("sqlmock_db_0")

    mockedGorm, _ := gorm.Open("sqlmock", "sqlmock_db_0")
    defer mockedGorm.Close()
    myDB := &DB{mockedGorm}

    mock.ExpectExec("INSERT INTO test").WithArgs("c").WillReturnResult(sqlmock.NewResult(1, 1))
    myDB.Exec("INSERT INTO test(first_name) VALUES (?)", "c")


    if _, err := myDB.CreateTest(); err != nil {
        t.Errorf("error was not expected: %s", err)
    }

    if err := mock.ExpectationsWereMet(); err != nil {
        t.Errorf("there were unfulfilled expectations: %s", err)
    }
}

不幸的是,这给了我一个错误:

error was not expected: all expectations were already fulfilled, call to database transaction Begin was not expected

如何正确测试带有 gorm、postgresql 和 sql-mock 的插入?

4

1 回答 1

2

我的代码有几个问题:

1) 正如@flimzy 正确指出的那样,必须有一个ExpectBegin()(and ExpectCommit()) 语句。如果打开显示 GORM 正在做什么的 GORM 调试器,这一点会变得更加明显。

2)ExpectExec("INSERT INTO test").WithArgs("c")很明显不匹配myDB.Exec("INSERT INTO test(first_name) VALUES (?)", "c")

3) 必须转义语句,因为 go-sqlmock 需要一个正则表达式,这里 Go 的https://godoc.org/regexp#QuoteMeta派上用场。

工作代码:

mock.ExpectBegin()
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO \"tests\" (\"first_name\") VALUES (?)")).WithArgs("c").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
于 2020-02-11T23:44:49.977 回答