1 回答

TA貢獻1806條經驗 獲得超5個贊
在您的測試中,您在數據庫提供者級別模擬數據庫,不再需要模擬。
沒有冗余模擬的測試:
func TestCalculate(t *testing.T) {
// transaction is created inside `CalculateTransaction`, it will be started against mocked DB
// var tx *sqlx.Tx
var expectedError string
dbMock, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected", err)
}
defer dbMock.Close()
// we use sql mock - no need to mock DB methods
// mockSQL = new(mocks.SQLRepository)
// mockSQL.On("BeginTX").Return(tx, nil)
mock.ExpectCommit()
// here you can add ExpectQuery or ExpectExec if usecase do any DB work
mock.ExpectRollback()
usecase := &calculationUsecase{
sqlRepo: dbMock
}
actualError := usecase.CalculateTransaction(context.Background(), 1)
require.EqualError(t, actualError, expectedError)
// it is good practice to check is all expectations are met
err = mock.ExpectationsWereMet()
require.NoError(t, err)
}
- 1 回答
- 0 關注
- 88 瀏覽
添加回答
舉報