3

我正在尝试使用 Data Doggo-sqlmocktestify.

我有以下代码:

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
4

2 回答 2

5

您需要在Test_repository_Creates.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()
于 2020-03-07T18:12:17.767 回答
-2

调用数据库事务开始,如果您将您的 gorm 版本更新到github.com/jinzhu/gorm v1.9.2或最新版本,则不会出现预期错误将得到解决

于 2020-05-21T11:12:17.523 回答