单元测试中的模拟是在单元测试中创建测试替身以替换外部依赖项的技术,允许隔离和测试特定函数。基本原则是:定义接口、创建模拟、注入模拟。使用 Googlemock 模拟,需要定义接口、创建模
单元测试中的模拟是在单元测试中创建测试替身以替换外部依赖项的技术,允许隔离和测试特定函数。基本原则是:定义接口、创建模拟、注入模拟。使用 Googlemock 模拟,需要定义接口、创建模拟、在测试函数中注入它。使用 testify/mock 模拟,需要声明 mockclient 结构体、为 get 方法设置期望值、在测试函数中设置模拟。
在单元测试中,模拟(mocking)是一种创建测试替身的技术,用于替换被测代码中的外部依赖。这允许您隔离和测试特定函数,而无需与其他组件交互。
模拟的基本原则是:
考虑以下使用 net/Http
包的函数:
func GetPage(url string) (*http.Response, error) {
client := http.Client{}
return client.Get(url)
}
要测试此函数,我们需要模拟 http.Client
,因为它是一个外部依赖项。
可以使用 GoogleMock 库进行模拟。首先,我们定义要模拟的接口:
type MockClient interface {
Get(url string) (*http.Response, error)
}
然后,我们可以使用 new(MockClient)
创建模拟,并在测试函数中注入它:
import (
"testing"
"<a style='color:#f60; text-decoration:underline;' href="https://www.PHP.cn/zt/15841.html" target="_blank">git</a>hub.com/<a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/16009.html" target="_blank">golang</a>/mock/gomock"
)
func TestGetPage(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := mock.NewMockClient(ctrl)
client.EXPECT().Get("http://example.com").Return(&http.Response{}, nil)
resp, err := GetPage("http://example.com")
assert.NoError(t, err)
assert.NotNil(t, resp)
}
testify/mock 库还提供了模拟功能。使用示例如下:
import (
"testing"
"GitHub.com/stretchr/testify/mock"
)
type MockClient struct {
mock.Mock
}
func (m *MockClient) Get(url string) (*http.Response, error) {
args := m.Called(url)
return args.Get(0).(*http.Response), args.Error(1)
}
func TestGetPage(t *testing.T) {
client := new(MockClient)
client.On("Get", "http://example.com").Return(&http.Response{}, nil)
resp, err := GetPage("http://example.com")
assert.NoError(t, err)
assert.NotNil(t, resp)
}
以上就是Go 函数单元测试中的模拟技巧的详细内容,更多请关注编程网其它相关文章!
--结束END--
本文标题: Go 函数单元测试中的模拟技巧
本文链接: https://www.lsjlt.com/news/611478.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0