英文:
Toggle Test Coverage with os.Getenv
问题
我正在进行一个简单的测试,并在Visual Studio Code
中使用Go: Toggle Test Coverage In Current Package
进行测试,就像这样<br>
在我的代码中,我使用os.Getenv
从我的环境中读取一个变量。<br>
使用os.Getenv
时,它返回FAIL
,但是硬编码时返回SUCCESS
<br>
<br>
如何在使用Go: Toggle Test Coverage In Current Package
时,即使从env
中获取数据,也能获得SUCCESS
?
这是我的代码:
type MyStruct struct {
Name string `json:"name"`
}
func MyFunc() ([]MyStruct, error) {
str := os.Getenv("MyStruct") // 失败
// str := `[{\"name\": \"one\"}, {\"name\": \"two\"}]` // 成功
var myData []MyStruct
err := json.Unmarshal([]byte(str), &myData)
if err != nil {
return nil, err
}
return myData, nil
}
我的测试代码:
func TestMyFunc(t *testing.T) {
tests := []struct {
name string
want []MyStruct
wantErr error
}{
{
name: "success",
want: []MyStruct{
{
Name: "one",
},
{
Name: "two",
},
},
wantErr: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := MyFunc()
assert.Equal(t, err, tt.wantErr)
assert.Equal(t, got, tt.want)
})
}
}
我的环境:
export MyStruct='[{\"name\": \"one\"}, {\"name\": \"two\"}]'
使用
英文:
I'm making a simple test, and test using Go: Toggle Test Coverage In Current Package
in Visual Studio Code
like this<br>
In my code is using os.Getenv
to read a variable from my own env.<br>
It get FAIL
when using os.Getenv
, but SUCCESS
when hardcoded<br>
<br>
How to get SUCCESS
even get data from env
using Go: Toggle Test Coverage In Current Package
?
Here is my code:
type MyStruct struct {
Name string `json:"name"`
}
func MyFunc() ([]MyStruct, error) {
str := os.Getenv("MyStruct") // Fail
// str := `[{"name": "one"}, {"name": "two"}]` // Success
var myData []MyStruct
err := json.Unmarshal([]byte(str), &myData)
if err != nil {
return nil, err
}
return myData, nil
}
My test code:
func TestMyFunc(t *testing.T) {
tests := []struct {
name string
want []MyStruct
wantErr error
}{
{
name: "success",
want: []MyStruct{
{
Name: "one",
},
{
Name: "two",
},
},
wantErr: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := MyFunc()
assert.Equal(t, err, tt.wantErr)
assert.Equal(t, got, tt.want)
})
}
}
My env:
export MyStruct='[{"name": "one"}, {"name": "two"}]'
Using
答案1
得分: 0
我找到了解决方案<br>
只需将以下代码添加到测试代码中:
strEnv := `[{"name": "one"}, {"name": "two"}]`
err := os.Setenv("MyStruct", strEnv)
if err != nil {
return
}
英文:
I found the solution<br>
Just add this code to test code:
strEnv := `[{"name": "one"}, {"name": "two"}]`
err := os.Setenv("MyStruct", strEnv)
if err != nil {
return
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论