Home > database >  Is there a best practice to setup golang unit test parameters?
Is there a best practice to setup golang unit test parameters?

Time:12-08

My unit test needs a remote server address to startup. The server address is not fixed.

If I put the address in my .go test source, I will change them everytime when I run it.

If I put them in system environment variable, it is very inconvenience to change it in VSCode GUI. (I mean I will start the test in VSCode menu.)

I known I can put environment variable in launch.json to setup before run or debug my program. But here I just want to run unit test.

Is there a good way to change the parameters without restarting the VSCode?

CodePudding user response:

You can add following snippets to VSCode settings.json to specify environment variables just for go test runs:

Defining variables directly:

"go.testEnvVars": {
  "MY_VAR": "my value"
},

Or using dedicated file (in my example called test.env in root of project workspace) containing the environment variables in MY_VAR="my value" format with one variable per line:

"go.testEnvFile": "${workspaceFolder}/test.env",

Also note that unit tests (as name suggests they test one unit of code) should generally not depend on any external services or resources. Everything except the logic under test should be provided in form of mocks.

  • Related