lundi 1 mars 2021

Unit test function that reads configuration file

I am learning Golang and was working on an application that reads a yaml configuration file and loads its contents into a struct. I'm adding tests to the app, and was wondering if there is a way of no having to pass a real file to ioutil.ReadFile and instead mock its contents. Let's say that the struct object of the configuration is something like:

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

And the function to read the configuration is:

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
}

Aucun commentaire:

Enregistrer un commentaire