Skip to content

sql mock案例

Jakegogo edited this page Jan 4, 2025 · 2 revisions

sql.go:

package example

import (
	"gorm.io/gorm"
)

// Product 模型
type Product struct {
	gorm.Model
	Code  string
	Price uint
}

// CallSQLQuery db 查询调用
func CallSQLQuery(db *gorm.DB, code string) (uint, error) {
	product := &Product{}
	err := db.First(product, "code = ?", code).Error
	if err != nil {
		return 0, err
	}

	return product.Price, nil
}

sql_test.go:

package example

import (
	"regexp"
	"testing"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func TestSQLQuery(t *testing.T) {
	// 初始化 sqlmock
	mockDB, mock, err := sqlmock.New()
	require.NoError(t, err)

	db, err := gorm.Open(mysql.New(mysql.Config{
		Conn:                      mockDB,
		SkipInitializeWithVersion: true, // 这个必须设置
	}), &gorm.Config{})
	require.NoError(t, err)

	// 设置语句匹配条件
	mock.ExpectQuery(
		regexp.QuoteMeta("SELECT * FROM `products` WHERE code = ?")).WithArgs("123").
		WillReturnRows(sqlmock.NewRows([]string{"price"}).AddRow(uint(1)))

	// 调用并断言
	price, err := CallSQLQuery(db, "123")
	assert.Equal(t, uint(1), price)
	assert.NoError(t, err)
}