80 lines
1.8 KiB
Markdown
80 lines
1.8 KiB
Markdown
# 程序配置管理
|
||
|
||
|
||
|
||
|
||
## 测试验证包
|
||
|
||
要考虑测序的是否如预期运行
|
||
|
||
## 如果定义单元测试
|
||
|
||
1. 包的命名规范: pkg_test
|
||
我想测试 LoadConfigFromYaml 这个函数能不能正常运行, Go里的每一个Package 都允许有2个包:
|
||
+ pkg: 目标包
|
||
+ pkg_test: 正对目标包的测试包
|
||
|
||
2. 定义测试函数: TestLoadConfigFromYaml(t *testing.T)
|
||
+ TestXXXX
|
||
+ (t *testing.T)
|
||
|
||
那么你的单元测试定义成功:
|
||

|
||
|
||
## 如何查看单测单元的信息
|
||
|
||
在单元测试里: 是不是被显示
|
||
```go
|
||
t.Log(config.Get())
|
||
```
|
||
|
||
我Run时, vscode生成的 go test命令
|
||
```sh
|
||
Running tool: /usr/local/go/bin/go test -timeout 300s -run ^TestLoadConfigFromYaml$ gitlab.com/go-course-project/go17/book/config -v -count=1
|
||
```
|
||
|
||
怎么才能配置vscode 添加go test的 参数, 你需要对的vscode做配置
|
||

|
||
|
||
修改 TestFlag
|
||
```json
|
||
"go.testFlags": [
|
||
"-v",
|
||
"-count=1"
|
||
],
|
||
```
|
||
+ -v 就是打印 debug信息, t.Log的信息
|
||
+ -count=1: 必须执行一次
|
||
|
||
## 为你的对象实现Stringger 接口
|
||
|
||
```go
|
||
// &{0x102317ec0 0x10231c8a0}
|
||
//
|
||
// String() string, fmt.Strigger接口
|
||
//
|
||
// fmt.
|
||
func (c *Config) String() string {
|
||
v, _ := json.Marshal(c)
|
||
return string(v)
|
||
}
|
||
```
|
||
|
||
```sh
|
||
/Users/yumaojun/Projects/go-course/go17/book/config/load_test.go:17: {"app":{"host":"localhost","port":8090},"mysql":{"host":"127.0.0.1","port":3306,"database":"test","username":"root","password":"888888","debug":false}}
|
||
```
|
||
|
||
```go
|
||
// Stringer is implemented by any value that has a String method,
|
||
// which defines the “native” format for that value.
|
||
// The String method is used to print values passed as an operand
|
||
// to any format that accepts a string or to an unformatted printer
|
||
// such as Print.
|
||
type Stringer interface {
|
||
String() string
|
||
}
|
||
```
|
||
|
||
## debug 测试
|
||
|