golang编写UT:applyFunc和applyMethod区别

GoConveygithub.com/smartystreets/goconvey/convey)中,ApplyFuncApplyMethod 都用于 mock(模拟)函数或方法,主要区别在于它们的作用对象不同:

函数 作用对象 用途
ApplyFunc 普通函数 Mock 一个全局函数或包级函数
ApplyMethod 结构体方法 Mock 某个结构体的实例方法

1️⃣ ApplyFunc 用于 Mock 普通函数

ApplyFunc 用于替换**包级函数(普通全局函数)**的实现,例如:

go 复制代码
package main

import (
	"fmt"
	"testing"

	. "github.com/smartystreets/goconvey/convey"
	"github.com/smartystreets/goconvey/convey/gomock"
)

// 目标函数
func GetData() string {
	return "Real Data"
}

func TestApplyFunc(t *testing.T) {
	Convey("Mock GetData function", t, func() {
		// Mock GetData,使其返回 "Mocked Data"
		reset := gomock.ApplyFunc(GetData, func() string {
			return "Mocked Data"
		})
		defer reset() // 确保测试结束后恢复原函数

		So(GetData(), ShouldEqual, "Mocked Data") // 断言函数返回值
	})
}

🔹 原理ApplyFunc(GetData, mockImplementation) 拦截GetData 函数的调用,并让它返回 "Mocked Data"


2️⃣ ApplyMethod 用于 Mock 结构体方法

ApplyMethod 用于 mock 某个结构体实例的方法,例如:

go 复制代码
package main

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
	"github.com/smartystreets/goconvey/convey/gomock"
)

// 结构体
type UserService struct{}

func (u *UserService) GetUserName() string {
	return "Real User"
}

func TestApplyMethod(t *testing.T) {
	Convey("Mock UserService.GetUserName method", t, func() {
		// Mock 结构体的 GetUserName 方法
		reset := gomock.ApplyMethod((*UserService)(nil), "GetUserName", func(_ *UserService) string {
			return "Mocked User"
		})
		defer reset() // 确保测试结束后恢复原方法

		service := &UserService{}
		So(service.GetUserName(), ShouldEqual, "Mocked User") // 断言方法返回值
	})
}

🔹 原理

  • ApplyMethod((*UserService)(nil), "GetUserName", mockImplementation) 拦截了 所有 UserService 实例GetUserName 方法,使其返回 "Mocked User"

🎯 总结

方法 Mock 目标 使用示例
ApplyFunc 普通函数 ApplyFunc(GetData, mockFunc)
ApplyMethod 结构体方法 ApplyMethod((*UserService)(nil), "MethodName", mockFunc)
  • ApplyFunc 适用于 :Mock 全局函数
  • ApplyMethod 适用于 :Mock 某个结构体的实例方法

🚀 什么时候用?

  • 当你在 单元测试 里,需要 隔离依赖的外部函数方法 ,避免真实逻辑执行,或者控制返回值 时,可以使用 ApplyFuncApplyMethod 来 Mock 这些函数/方法。
相关推荐
江小康1 分钟前
深入理解 C 语言的 undefined behavior:一行代码引发的惨案 !
c语言·后端
全栈派森2 分钟前
从SQL到向量:解锁MySQL+RAG的高效语义检索与AI应用落地
后端·python
Asthenia04123 分钟前
深入理解G1垃圾回收器:GC Roots与标记机制的“人性化”探秘
后端
用户613346716535 分钟前
开发体育赛事直播系统:炫彩弹幕直播间界面技术实现方案
前端·后端
uhakadotcom9 分钟前
Kafka和PySpark:基础知识与应用场景
后端·面试·github
努力学习的小廉23 分钟前
【C++】 —— 笔试刷题day_9
开发语言·c++·代理模式
Yhame.24 分钟前
【 C 语言实现顺序表的基本操作】(数据结构)
c语言·开发语言·数据结构
eqwaak028 分钟前
京东商品爬虫技术解析:基于Selenium的自动化数据采集实战
开发语言·人工智能·爬虫·python·selenium·自动化
Asthenia041239 分钟前
面试复盘:项目中OOM的那些事儿——原因、排查与代码反思
后端
uhakadotcom40 分钟前
使用 Apache Dubbo-Python 构建高性能 RPC 服务
后端·面试·github