设置自定义 HTTP 客户端的接口步骤
时间:2024-02-12
浏览:294
作者:佚名
亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《设置自定义 HTTP 客户端的接口步骤》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。
我在为我导入的第 3 方库编写测试时遇到困难。我认为这是因为我希望我的 customclient 结构具有 client 接口而不是 *banker.client 。这使得测试变得非常困难,因为很难模拟 *banker.client。有什么想法可以正确地将其转变为界面吗?所以我可以轻松地针对它编写模拟测试并设置一个假客户端?
type customclient struct {
client *banker.client //i want to change this to an interface
name string
address string
}
func (c *customclient) sethttpclient(httpclient *banker.client) { //i want to accept an interface so i can easily mock this.
c.client = httpclient
}
问题是banker.client是我正在导入的第三方客户端,其中包含许多结构和其他字段。它看起来像这样:
type client struct {
*restclient.client
monitor *monitors
pricing *pricing
verifications *verifications
}
最终结果是我的代码如下所示:
func (c *CustomClient) RequestMoney() {
_, err := v.client.Verifications.GetMoney("fakeIDhere")
}正确答案
考虑到结构体上字段的方法,这肯定不是一个简单的解决方案。但是,我们可以尝试尽量减少当前包上冗长的测试用例。
在您的工作包和银行家之间添加另一个层(包)。简化示例中的代码进行解释。
假设您的 banker 包包含以下代码:
type client struct {
verification *verification
}
type verification struct{}
func (v verification) getmoney(s string) (int, error) {
...
}
创建另一个导入银行家并定义接口的包,例如 bankops 包:
type bank struct {
bankclient *banker.client
}
type manager interface {
getmoney(s string) (int, error)
}
func (b *bank) getmoney(s string) (int, error) {
return b.bankclient.verification.getmoney(s)
}
注意:实际问题(没有接口的测试)仍然在bankops包中,但这更容易测试,因为我们只转发结果。服务于单元测试的目的。
最后,在当前的包中(对我来说是main包),我们可以
type customclient struct {
client bankops.manager
}
func (c *customclient) requestmoney() {
_, err := c.client.getmoney("fakeidhere")
...
}
func main() {
client := &customclient{
client: &bankops.bank{
bankclient: &banker.client{
verification: &banker.verification{},
},
},
}
client.requestmoney()
}
有关工作示例,请查看 Playground。
您可以像在原始代码片段中所做的那样添加 setters 或 builders 模式 以使字段(如 bankerclient)不导出。
我认为不可能将其直接放入界面
因为我们应该使用client的成员变量。
将其成员变成接口怎么样? 例如,
for _, test := []struct{}{
testVerification VerificationInterface
}{{
testVerification: v.Client.Verifications
},{
testVerification: VerficationMock
}}{
// test code here
}终于介绍完啦!小伙伴们,这篇关于《设置自定义 HTTP 客户端的接口步骤》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
