我正在尝试使用 Data Doggo-sqlmock
和testify
.
我有以下代码:
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
函数是否正在运行? - 为什么
? my-project [no test files]
我跑步时会得到go test
?这是上面代码的文件路径:my-project/test/models/User_test.go