gpt4 book ai didi

unit-testing - 读取配置文件的单元测试函数

转载 作者:行者123 更新时间:2023-12-01 23:29:59 24 4
gpt4 key购买 nike

我正在学习 Golang,并且正在开发一个读取 yaml 配置文件并将其内容加载到结构中的应用程序。我正在向应用程序添加测试,想知道是否有一种方法可以不必将真实文件传递给 ioutil.ReadFile 而是模拟其内容。假设配置的结构对象类似于:

type AppConfig struct {
someConfig string `yaml:"someConfig"`
someOtherConfig string `yaml:"someOtherConfig"`
}

读取配置的函数是:

func readConfig(filePath string) (*AppConfig, error) {

file, err := ioutil.ReadFile(filePath)

if err != nil {
log.Fatal(err)
}

conf := AppConfig{}
err = yaml.Unmarshal([]byte(file), &conf)
if err != nil {
return &AppConfig{}, err
}

fmt.Printf("\n%#v\n", conf)

return &conf, nil
}

最佳答案

我会将函数拆分为一个用于读取的函数和一个用于将数据解码到 conf 中的函数。将第一个函数的结果(文件内容)传递给第二个函数。然后就可以轻松测试第二个功能了。

另一种选择是将 ioutil.ReadFile(filePath) 包装到辅助函数中,并在测试 readConfig() 时模拟该函数。

关于unit-testing - 读取配置文件的单元测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66430403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com