1 回答
TA贡献1825条经验 获得超4个赞
可测试代码的一个非常基本的规则是,您不能只在其他服务中创建新服务。您需要注入它,并准备一个接口(如果返回的内容还没有接口的话)resty.New。这样你就可以在测试中注入你的模拟。
然后你可以使用例如https://pkg.go.dev/github.com/stretchr/testify/mock来生成模拟并说明你的模拟服务应该返回什么值。
评论后更新:
type HttpClient struct {
logger *logger.Logger
config *config.Server
instrumentation *instrumentation
record *logger.LogRecord
restyClient *resty.Client // <- this is the thing you want to change from a pointer to resty.Client to an interface
}
检查restyClient您在代码中使用了哪些方法,并创建包含它们的新接口,例如:
type MyRestyClient interface {
FirstUsedMethod(..)
...
}
并将 restyClient 声明交换为
type HttpClient struct {
...
restyClient MyRestyClient
之后,您可以使用我之前粘贴的链接中的模拟和命令为您生成模拟。
稍后,您只需在测试中设置模拟:
restyMock := new(RestyMock)
restyMock.On("MethodYouExpect").Return(returnValueOfYourChoice)
然后您将准备好的模拟注入到您的测试服务中。
- 1 回答
- 0 关注
- 140 浏览
添加回答
举报
