登录
首页 >  Golang >  Go问答

读取配置文件的单元测试功能

来源:stackoverflow

时间:2024-03-16 14:48:29 286浏览 收藏

在 Go 语言中,读取配置文件并将其内容加载到结构中时,可以使用单元测试来验证应用程序的行为。对于涉及读取实际文件的函数,可以考虑模拟文件内容来避免在测试中使用真实文件。一种方法是将读取操作和解组操作拆分为两个函数,并在测试时传递模拟的文件内容。另一种选择是将读取文件操作包装到一个辅助函数中,并使用接口来模拟该函数。通过这些方法,可以轻松地测试配置文件读取功能,而无需依赖于实际的文件系统操作。

问题内容

我正在学习 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() 时模拟该函数。

可以通过使用接口和稍作修改。

// defining an interface so that functionality of 'readconfig()' can be mocked
type ireader interface{
    readconfig() ([]byte, error)
}

type reader struct{
    filename string
}

// 'reader' implementing the interface
// function to read from actual file
func (r *reader) readconfig() ([]byte, error) {
    file, err := ioutil.readfile(r.filename)

    if err != nil {
        log.fatal(err)
    }
    return file, err
}

修改原来的代码来读取和设置config:

type appconfig struct {
    someconfig       string `yaml:"someconfig"`
    someotherconfig  string `yaml:"someotherconfig"`
}

// function takes the mentioned interface as a parameter
func getconfig(reader ireader) (*appconfig, error) {
    file, err :=reader.readconfig()

    conf := appconfig{}
    err = yaml.unmarshal(file, &conf)
    if err != nil {
        return &appconfig{}, err
    }

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

    return &conf, nil
}

当你想使用实际方法阅读时:

func main() {
    reader := reader{filename:"actual file name"}
    configval, err := getconfig(&reader)
    fmt.println("values received from file: ", configval, err)
}

现在,开始测试代码:

type readerTest struct {
    fileName string
}

// 'readerTest' implementing the Interface
func (r *readerTest) readConfig() ([]byte, error) {
    // Prepare data you want to return without reading from the file
    return []byte{}, nil
}

func TestGetConfig() {
    testReader := readerTest{fileName:"Sample File Name"}
    configVal, err := getConfig(&testReader)
    fmt.Println("Write tests on values: ", configVal, err)
}

以上就是《读取配置文件的单元测试功能》的详细内容,更多关于的资料请关注golang学习网公众号!

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