falcon-plus icon indicating copy to clipboard operation
falcon-plus copied to clipboard

建议对单元测试友好点

Open shaneing opened this issue 6 years ago • 0 comments

比如,配置加载这里:

var config     *GlobalConfig
func ParseConfig(cfg string) {
	...
	var c GlobalConfig
	err = json.Unmarshal([]byte(configContent), &c)
	if err != nil {
		log.Fatalln("parse config file:", cfg, "fail:", err)
	}

	lock.Lock()
	defer lock.Unlock()

	config = &c

	log.Println("read config file:", cfg, "successfully")
}

由于 config 是包私有的,所以无法直接初始化,只能通过 ParseConfig 方法进行初始化,但这对单元测试不友好。我这里改了下:

func ParseConfig(cfg string) {
        ...
	lock.Lock()
	defer lock.Unlock()
	
	err = json.Unmarshal([]byte(configContent), &config)
	if err != nil {
		log.Fatalln("parse config file:", cfg, "fail:", err)
	}
	
	log.Println("read config file:", cfg, "successfully")
}

func init() {
	config = &GlobalConfig{}
}

这样,这样初始化后,我就能直接调用 g.Config() 对其成员进行初始化。

shaneing avatar Nov 04 '19 10:11 shaneing