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

标签 unit-testing go testing

我正在学习 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/

相关文章:

c# - 使用 Moq 使用内部构造函数模拟类型

Android 从终端终止应用程序

visual-c++ - 如何在 VC++ 中的另一个测试项目中使用来自一个测试项目的类?

golang 静态停止 index.html 重定向

caching - 在Golang的不同包中获取Redis变量

go - 如何在 Java 中编写等同于匿名类的内容?

testing - Selenium:我可以在 Selenium 中设置 WebElement 的任何属性值吗?

c++ - 如何在 C++ 中使用 GMock 模拟方法(非虚拟)以返回特定值?

unit-testing - jest.fn() 有什么作用以及如何使用它?

angular - Angular 构造函数中的单元测试函数调用