登录
首页 >  Golang >  Go问答

模拟外部库进行单元测试

来源:stackoverflow

时间:2024-04-07 15:06:34 412浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《模拟外部库进行单元测试》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我有一个下面的函数 tryget() 来进行单元测试:

type config struct {
    key      string        `json:"key"`
    client   todo.client  `json:"client"`
}

var instance *config

func (c *config) tryget() error {
    client := &http.client{}
    tclient := client{"http://url", client}
    configvalues := config{"key", tclient} 
    instance := &configvalues
    err := instance.client.perform("get", header)
    return nil
}

// 名为“todo”的包中的外部库具有以下结构和函数

package todo
type Client struct {
    BaseURL         string
    HTTPClient      *http.Client
}

func (client *Client) perform() error {

    return nil
}

我发现很难模拟客户端并在外部包待办事项中执行


解决方案


如果外部库不在您的控制之下(我认为是这种情况),那么您应该假设内部的代码已经过测试,因此您应该在您可以控制代码的点创建边界。 p>

为此,您应该在配置结构边界创建接口。

type ClientInterface interface {
    perform() error
}

type config struct {
    Url      string            `json:"url"`
    Client   ClientInterface   `json:"client"`
}

var instance *config

func (c *config) tryGet() error {
    err := c.Client.perform("GET", header)
    return nil
}

通过这种方式,您不必关心测试较低级别的代码库,您只关心该模块具有执行功能,并且在给定某些条件下您的代码行为正确。

然后,您可以创建一个模拟 todo.cient 结构,您可以用它替换普通的结构,并让它返回各种事物和行为来测试您的代码。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《模拟外部库进行单元测试》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>