Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 测试在Golang中加载JSON配置文件的方法_Unit Testing_Go_Testify - Fatal编程技术网

Unit testing 测试在Golang中加载JSON配置文件的方法

Unit testing 测试在Golang中加载JSON配置文件的方法,unit-testing,go,testify,Unit Testing,Go,Testify,在测试项目中,有一个方法将JSON配置文件加载到变量中。其代码如下: // Load the JSON config file func Load(configFile string, outputObj interface{}) *errors.ErrorSt { var err error // Read the config file jsonBytes, err := ioutil.ReadFile(configFile) if err != nil {

在测试项目中,有一个方法将JSON配置文件加载到变量中。其代码如下:

// Load the JSON config file
func Load(configFile string, outputObj interface{}) *errors.ErrorSt {
    var err error
    // Read the config file
    jsonBytes, err := ioutil.ReadFile(configFile)
    if err != nil {
        fmt.Println(err.Error())
        return errors.File().AddDetails(err.Error())
    }

    // Parse the config
    if err := json.Unmarshal(jsonBytes, outputObj); err != nil {
        return errors.JSON().AddDetails("Could not parse" + configFile + ": " + err.Error())
    }
    return nil

}
我希望测试它,但我不知道是应该为测试用例创建假JSON文件,还是只是模拟整个函数。我的Java背景使我倾向于后者


探索这一点,我发现了我正在使用的
验证
框架,但我试图模拟的不属于接口(非OOP语言的陷阱!!)

有几种方法可以做到这一点。有一个示例数据文件来测试加载和解析文件(您可以在标准库中的某些地方找到)当然并不少见。对于像这样的函数来说,采用
io.Reader
而不是文件路径也是一种非常常见的做法,因此在测试中,您可以只传入一个
bytes.Reader
,以便在测试其他所有内容时有效地“模拟”文件。使用哪种方法(或两者,如果您选择)取决于您的用例和设计目标;切换到
io.Reader
会给您带来更多的灵活性,但只有您知道这种灵活性在上下文中是否有任何价值。如果没有,只需在测试中保留一个测试文件并阅读即可