我试图使用Data的go-sqlmock和testify在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我有几个问题:
SetupSuite函数是否正在运行?go test时得到? my-project [no test files]?这是上面代码的文件路径:my-project/test/models/User_test.go发布于 2020-03-07 18:12:17
您需要在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()https://stackoverflow.com/questions/58804606
复制相似问题