我正在学习Golang,并且正在开发一个可以读取yaml配置文件并将其内容加载到结构中的应用程序。我正在向应用程序添加测试,我想知道是否有一种方法可以不必将真正的文件传递给
取而代之的是嘲笑它的内容。假设配置的struct对象类似于:
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
}
发布于 2021-03-01 22:18:54
我会把这个函数分成两部分,一个负责读取,另一个负责解组
..。将第一个函数的结果(文件内容)传递给第二个函数。然后,您可以轻松地测试第二个函数。
另一种选择是包装
转换为帮助器函数,并在测试时模拟该函数
..。
发布于 2021-03-02 07:12:31
通过接口的使用和少量的修改,就可以很容易地完成这项工作。
// 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)
}
https://stackoverflow.com/questions/66430403
复制相似问题