0

I'm making a simple test, and test using Go: Toggle Test Coverage In Current Package in Visual Studio Code like this
vscode

In my code is using os.Getenv to read a variable from my own env.
It get FAIL when using os.Getenv, but SUCCESS when hardcoded

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

Gama11
  • 31,714
  • 9
  • 78
  • 100
Gerald Sihotang
  • 265
  • 5
  • 18
  • 1
    this should answer your question https://stackoverflow.com/questions/48595446/is-there-any-way-to-set-environment-variables-in-visual-studio-code/48609350 – Wishwa Perera Jun 30 '21 at 04:57

1 Answers1

0

I found the solution
Just add this code to test code:

strEnv := `[{"name": "one"}, {"name": "two"}]`
err := os.Setenv("MyStruct", strEnv)
if err != nil {
    return
}
Gerald Sihotang
  • 265
  • 5
  • 18