我正在尝试使用 testify 在 Go 上创建单元测试。我要测试的函数非常简单,它会启动一个 SQL 事务,然后通过回购层从数据库中获取值,然后计算这些值。但是每当我尝试运行单元测试时,我总是遇到这个错误。
# go test -v usecase/calculate_test.go usecase/calculate.go usecase/other_related_usecase.go
=== RUN Test_Calculate
[2022-07-15 08:42:30] INFO: Start Calculation
--- FAIL: Test_Calculate (0.00s)
panic:
assert: mock: I don't know what to return because the method call was unexpected.
Either do Mock.On("BeginTxx").Return(...) first, or remove the BeginTxx() call.
This method was unexpected:
BeginTxx()
at: [sql_repository.go:1 calculate.go:4 calculate_test.go:2] [recovered]
panic:
assert: mock: I don't know what to return because the method call was unexpected.
Either do Mock.On("BeginTxx").Return(...) first, or remove the BeginTxx() call.
This method was unexpected:
BeginTxx()
at: [sql_repository.go:1 calculate.go:4 calculate_test.go:2]
据我所知,我认为这是因为它无法在单元测试中找到预期的方法调用。但是,问题是我已经在onSQLMock字段中定义了方法调用。
func Test_Calculate(t *testing.T) {
testCases := []struct {
name string
id int64
onSQLMock func(sqlMock *mocks.SQLRepository)
onOtherFuncMock func(otherFuncMock *mocks.OtherFuncMock)
wantError bool
expectedError string
}{
{
name: "Successfully Calculated",
onSQLMock: func(sqlMock *mocks.SQLRepository) {
var tx *sqlx.Tx
sqlRepo.On("BeginTxx").Return(tx, nil)
},
onOtherFuncMock: func(otherFuncMock *Mocks.OtherFuncMock) {
// do something here
},
wantError: false,
},{
name: "Failed to calculate",
onSQLMock: func(sqlMock *mocks.SQLRepository) {
var tx *sqlx.Tx
sqlRepo.On("BeginTxx").Return(tx, errors.New("Failed to begin tx")
},
onOtherFuncMock: func(otherFuncMock *mocks.OtherFuncMock) {
// do something here
},
wantError: true,
expectedError: "Failed to begin tx",
},
}
}
千巷猫影
相关分类