进行单元测试-调用数据库事务开始,这不是预期的错误

时间:2019-11-11 15:51:42

标签: go go-gorm testify go-sqlmock

我正在尝试使用Data Dog的go-sqlmocktestify在Go中编写模型单元测试。

我有以下代码:

type Suite struct {
    suite.Suite
    DB *gorm.DB
    mock sqlmock.Sqlmock

    repository      Repository
    user *models.User
}

func (s *Suite) SetupSuite() {
    var (
        db  *sql.DB
        err error
    )

    db, s.mock, err = sqlmock.New()
    require.NoError(s.T(), err)

    s.DB, err = gorm.Open("mysql", db)
    require.NoError(s.T(), err)

    s.DB.LogMode(true)

    s.repository = CreateRepository(s.DB)
}

func (s *Suite) AfterTest(_, _ string) {
    require.NoError(s.T(), s.mock.ExpectationsWereMet())
}

func TestInit(t *testing.T) {
    suite.Run(t, new(Suite))
}

func (s *Suite) Test_repository_Get() {
    var (
        ID        = 1234
        CountryID = 1
    )

    s.mock.ExpectQuery(regexp.QuoteMeta(
        `SELECT * FROM "User" WHERE (id = $1)`)).
        WithArgs(strconv.Itoa(ID)).
        WillReturnRows(sqlmock.NewRows([]string{"ID", "CountryID"}).
            AddRow(strconv.Itoa(ID), strconv.Itoa(CountryID)))

    res, err := s.repository.Get(ID)

    require.NoError(s.T(), err)
    require.Nil(s.T(), deep.Equal(&models.User{ID: ID, CountryID: CountryID}, res))
}

func (s *Suite) Test_repository_Create() {
    var (
        ID        = 1234
        CountryID = 1
    )

    s.mock.ExpectQuery(regexp.QuoteMeta(
        `INSERT INTO "User" ("ID","CountryID") 
            VALUES ($1,$2) RETURNING "User"."ID"`)).
        WithArgs(ID, CountryID).
        WillReturnRows(
            sqlmock.NewRows([]string{"ID"}).AddRow(strconv.Itoa(ID)))

    err := s.repository.Create(ID, CountryID)

    require.NoError(s.T(), err)
}

但是当我运行TestInit时,出现以下错误:

> call to database transaction Begin, was not expected, next expectation
> is: ExpectedQuery => expecting Query, QueryContext or QueryRow which:
>   - matches sql: 'INSERT INTO "User" \("ID","CountryID"\)             VALUES \(\$1,\$2\) RETURNING "User"\."ID"'
>   - is with arguments:
>     0 - 1234
>     1 - 1
>   - should return rows:
>     row 0 - [1234] [0m

我有几个问题:

  1. 这是什么问题?
  2. 有没有办法知道SetupSuite函数是否正在运行?
  3. 为什么我运行? my-project [no test files]时会得到go test?这是上面代码的文件路径:my-project/test/models/User_test.go

2 个答案:

答案 0 :(得分:0)

您需要在 Test_repository_Create 上添加s.mock.ExpectBegin()s.mock.ExpectCommit()

s.mock.ExpectBegin()
s.mock.ExpectQuery(regexp.QuoteMeta(
        `INSERT INTO "User" ("ID","CountryID") 
            VALUES ($1,$2) RETURNING "User"."ID"`)).
        WithArgs(ID, CountryID).
        WillReturnRows(
            sqlmock.NewRows([]string{"ID"}).AddRow(strconv.Itoa(ID)))
s.mock.ExpectCommit()

答案 1 :(得分:0)

调用数据库事务开始,如果将gorm版本更新到 github.com/jinzhu/gorm v1.9.2

,则不会解决错误。