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 这些函数/方法。
相关推荐
西阳未落2 小时前
C++基础(21)——内存管理
开发语言·c++·面试
我的xiaodoujiao2 小时前
Windows系统Web UI自动化测试学习系列2--环境搭建--Python-PyCharm-Selenium
开发语言·python·测试工具
callJJ2 小时前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(2)
java·开发语言·后端·spring·ioc·di
hsjkdhs4 小时前
万字详解C++之构造函数析构函数
开发语言·c++
你的人类朋友4 小时前
JWT的组成
后端
Lin_Aries_04214 小时前
容器化简单的 Java 应用程序
java·linux·运维·开发语言·docker·容器·rpc
techdashen5 小时前
12分钟讲解Python核心理念
开发语言·python
北风朝向5 小时前
Spring Boot参数校验8大坑与生产级避坑指南
java·spring boot·后端·spring
山海不说话5 小时前
Java后端面经(八股——Redis)
java·开发语言·redis
郝学胜-神的一滴5 小时前
谨慎地迭代函数所收到的参数 (Effective Python 第31条)
开发语言·python·程序人生·软件工程