巧用 Golang 函数特性实现单元测试中的数据库操作 Mock

背景

在实际开发过程中,我们常常面临这样的场景:当新增需求只是在原有逻辑基础上增加一小部分功能时,全面的接口测试显得冗余;而复杂业务逻辑的测试又面临造数据难、并发场景模拟复杂等问题。此时,单元测试的优势便凸显出来。

然而,单元测试中频繁的数据库操作会带来新的困扰:测试用例与数据库数据强耦合,不仅需要专门构造测试数据,还可能因数据库数据变更导致测试用例失效,增加问题定位成本。针对这些痛点,本文将介绍一种基于 Golang 特性的解决方案。

解决方案:利用 Golang 函数特性实现 Mock

Golang 中,函数被视为 "一等公民"------ 这意味着函数与变量具有同等地位,可以像变量一样作为参数传递、赋值或存储。正是这一特性,为我们提供了一种简洁高效的 Mock 实现方式。

核心实现思路

我们可以将数据库操作封装为函数变量,在业务代码中通过这些变量调用数据库方法;而在单元测试时,重新赋值这些函数变量,从而替代实际的数据库操作。

例如,定义如下函数变量用于数据库查询:

Go 复制代码
var GetRecordCountByCardId = func(ctx context.Context, giftCardId string, event int) (int64, error) {
    return new(models.GiftCardLogs).GetRecordCountByCardId(ctx, giftCardId, event)
}

在单元测试中,我们可以这样重新赋值以模拟数据库查询结果:

Go 复制代码
   GetRecordCountByCardId = func(ctx context.Context, cardNum string, event int) (int64, error) {
        return 2, nil
    }

通过这种方式,单元测试无需执行实际的数据库查询,彻底消除了与数据库数据的耦合。

完整示例代码

Go 复制代码
package gift_card_service

import (
	"context"
	"sync"
	"testing"

	"github.com/stretchr/testify/assert"
)


// 测试正常发生告警场景
func TestSendDuplicateActivetaAlert_Sucess(t *testing.T) {
	ctx := context.Background()
	ctx = context.WithValue(ctx, "trace_id", "test_trace_123456")
	cardNum := "test_12345"
	customerId := int64(37856993)
	event := 3
	//mock操作
	GetRecordCountByCardId = func(ctx context.Context, cardNum string, event int) (int64, error) {
		return 2, nil
	}
	//mock操作
	GetCustomerById = func(ctx context.Context, customerId int64) (models.Customer, error) {
		return models.Customer{
			Phone: "13812345678",
		}, nil
	}
	err := sendDuplicateActivateAlert(ctx, customerId, cardNum, event)
	if err != nil {
		assert.Error(t, err)
	}
}

// 测试并行运行
// 模拟两次从数据库查询获得的记录,一次是1,一次是2
// 预期结果:只发送一次告警
func TestSendDuplicateActivateAlert_Concurrency(t *testing.T) {
	ctx := context.Background()
	ctx = context.WithValue(ctx, "trace_id", "test_concurrency_hit")
	cardNum := "test_concurrency_123"
	customerId := int64(37856994)
	event := 3

	//测试并发执行,只发一次告警,起两个协程并发执行
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		//mock操作
		GetRecordCountByCardId = func(ctx context.Context, cardNum string, event int) (int64, error) {
			return 1, nil
		}
		//mock操作
		GetCustomerById = func(ctx context.Context, customerId int64) (models.Customer, error) {
			return models.Customer{
				Phone: "13812345678",
			}, nil
		}
		defer wg.Done()
		err := sendDuplicateActivateAlert(ctx, customerId, cardNum, event)
		assert.NoError(t, err)
	}()
	go func() {
		//mock操作
		GetRecordCountByCardId = func(ctx context.Context, cardNum string, event int) (int64, error) {
			return 2, nil
		}
		//mock操作
		GetCustomerById = func(ctx context.Context, customerId int64) (models.Customer, error) {
			return models.Customer{
				Phone: "13812345678",
			}, nil
		}
		defer wg.Done()
		err := sendDuplicateActivateAlert(ctx, customerId, cardNum, event)
		assert.NoError(t, err)
	}()
	wg.Wait()
}

// 测试并行运行
// 模拟两次从数据库查询获得的记录都是2的情况
// 期望只发送一次告警
func TestSendDuplicateActivateAlert_Concurrency_RecordCountEqual2(t *testing.T) {
	ctx := context.Background()
	ctx = context.WithValue(ctx, "trace_id", "test_concurrency_recordcountequal2")
	cardNum := "test_concurrency_recordcountequal2_123"
	customerId := int64(37856994)
	event := 3
	//测试并发执行,只发一次告警,起两个协程并发执行
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		//mock操作
		GetRecordCountByCardId = func(ctx context.Context, cardNum string, event int) (int64, error) {
			return 2, nil
		}
		//mock操作
		GetCustomerById = func(ctx context.Context, customerId int64) (models.Customer, error) {
			return models.Customer{
				Phone: "13812345678",
			}, nil
		}
		defer wg.Done()
		err := sendDuplicateActivateAlert(ctx, customerId, cardNum, event)
		assert.NoError(t, err)
	}()
	go func() {
		//mock操作
		GetRecordCountByCardId = func(ctx context.Context, cardNum string, event int) (int64, error) {
			return 2, nil
		}
		//mock操作
		GetCustomerById = func(ctx context.Context, customerId int64) (models.Customer, error) {
			return models.Customer{
				Phone: "13812345678",
			}, nil
		}
		defer wg.Done()
		err := sendDuplicateActivateAlert(ctx, customerId, cardNum, event)
		assert.NoError(t, err)
	}()
	wg.Wait()
}

// 测试激活记录数不足场景
func TestSendDuplicateActivateAlert_RecordCountLessThan2(t *testing.T) {
	ctx := context.Background()
	ctx = context.WithValue(ctx, "trace_id", "test_trace_count_less")
	cardNum := "test_count_less_456"
	customerId := int64(37856995)
	event := 3

	GetRecordCountByCardId = func(ctx context.Context, cardNum string, event int) (int64, error) {
		return 1, nil // 记录数小于2
	}
	//mock操作
	GetCustomerById = func(ctx context.Context, customerId int64) (models.Customer, error) {
		return models.Customer{
			Phone: "13812345678",
		}, nil
	}
	// 执行测试
	err := sendDuplicateActivateAlert(ctx, customerId, cardNum, event)

	// 断言结果
	assert.NoError(t, err)
}
Go 复制代码
func isSendAlert(ctx context.Context, cardNum string) (bool, error) {
	redisKey := cache.GiftCard[fmt.Sprintf(cache.GiftCard["duplicate_alert"], cardNum)]
	id, err := redis.NewIncrement(redisKey, 30*time.Second).GetIncrementID(ctx)
	if err != nil {
		// 失败了,发送告警,宁可重复发送,不要漏掉发送
		return false, err
	}
	if id > 1 {
		return true, nil
	}
	return false, nil
}

// 主要是为了测试用例中,mock操作,屏蔽数据库操作
var GetRecordCountByCardId = func(ctx context.Context, giftCardId string, event int) (int64, error) {
	return new(models.GiftCardLogs).GetRecordCountByCardId(ctx, giftCardId, event)
}

// 主要是为了测试用例中,mock操作,屏蔽数据库操作
var GetCustomerById = func(ctx context.Context, customerId int64) (models.Customer, error) {
	return models.GetCustomerById(ctx, customerId)
}

// 发送重复激活告警
func sendDuplicateActivateAlert(ctx context.Context, customerId int64, cardNum string, event int) error {
	// 1. 查询礼品卡激活记录数
	count, err := GetRecordCountByCardId(ctx, cardNum, event)
	if err != nil {
		return err
	}
	log.InfoWithCtx(ctx, "查询礼品卡激活记录数结果", zap.String("cardNum", cardNum), zap.Int64("count", count))

	if count < 2 {
		return nil
	}
	// 2. 检查并设置告警缓存,防止重复发送
	isSend, err := isSendAlert(ctx, cardNum)
	if err != nil {
		log.ErrorWithCtx(ctx, "检查重复激活告警缓存失败", zap.String("cardNum", cardNum), zap.Error(err))
	}
	if isSend {
		log.InfoWithCtx(ctx, "重复激活告警已发送过,跳过本次发送", zap.String("cardNum", cardNum))
		return nil
	}
	// 3. 根据customerId查询手机信息
	var customerInfo string
	customer, err := GetCustomerById(ctx, customerId)
	if err != nil {
		log.ErrorWithCtx(ctx, "查询用户信息失败", zap.Int64("customerId", customerId), zap.Error(err))
		customerInfo = strconv.FormatInt(customerId, 10)
	} else {
		customerInfo = customer.Phone
	}

	// 4. 拼接告警模板
	alarmTime := time.Now().Format("2006-01-02 15:04:05")
	msg := fmt.Sprintf(`事务名称:礼品卡异常
    异常内容:礼品卡重复激活
    异常账号:%s
    告警时间:%s
    其他信息:卡号:%s,重复激活次数:%d`,
		customerInfo, alarmTime, cardNum, count)

	// 5. 调用超紧急告警接口(使用传入的ctx而非新创建的上下文)
	if err := qiyewx_robot_service.QiWeiUrgentAlarm(ctx, msg); err != nil {
		return err
	}

	log.InfoWithCtx(ctx, "重复激活告警已成功发送", zap.String("cardNum", cardNum), zap.String("customerInfo", customerInfo))
	return nil
}

方案优势

  1. 解耦数据库依赖:单元测试不再依赖实际数据库,避免因数据变化导致测试用例失效。

  2. 简化测试数据准备:无需构造复杂的数据库数据,通过 Mock 函数直接返回预设结果。

  3. 提升测试效率:省去数据库交互开销,大幅加快单元测试执行速度。

  4. 覆盖特殊场景:轻松模拟并发、异常等难以通过接口测试复现的场景。

  5. 保持代码简洁:无需引入复杂的 Mock 框架,利用 Golang 原生特性即可实现 Mock 功能。

这种方案特别适合业务逻辑复杂、数据库操作频繁的场景,既能保证单元测试的独立性和稳定性,又能降低测试维护成本,是 Golang 项目中值得推广的单元测试实践方式。

相关推荐
艾莉丝努力练剑7 分钟前
【数据结构与算法】数据结构初阶:详解顺序表和链表(五)——双向链表
c语言·开发语言·数据结构·学习·算法
算法_小学生25 分钟前
Hinge Loss(铰链损失函数)详解:SVM 中的关键损失函数
开发语言·人工智能·python·算法·机器学习·支持向量机
paopaokaka_luck38 分钟前
基于SpringBoot+Vue的汽车租赁系统(协同过滤算法、腾讯地图API、支付宝沙盒支付、WebsSocket实时聊天、ECharts图形化分析)
vue.js·spring boot·后端·websocket·算法·汽车·echarts
giao源44 分钟前
Spring Boot 整合 Shiro 实现单用户与多用户认证授权指南
java·spring boot·后端·安全性测试
YUJIANYUE44 分钟前
纯前端html实现图片坐标与尺寸(XY坐标及宽高)获取
开发语言·前端·javascript
【本人】1 小时前
Django基础(四)———模板常用过滤器
后端·python·django
kyle~1 小时前
C++---cout、cerr、clog
开发语言·c++·算法
豌豆花下猫2 小时前
Python 潮流周刊#111:Django迎来 20 周年、OpenAI 前员工分享工作体验(摘要)
后端·python·ai
thginWalker2 小时前
拓扑排序/
java·开发语言