有没有一种最佳实践来设置Golang单元测试的参数?

huangapple go评论88阅读模式
英文:

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

问题

我的单元测试需要一个远程服务器地址来启动。服务器地址是不固定的。

如果我把地址放在我的.go测试源代码中,每次运行时都需要更改它们。

如果我把它们放在系统环境变量中,那么在VSCode GUI中更改它们会非常不方便。(我的意思是我会在VSCode菜单中启动测试。)

我知道我可以在launch.json中设置环境变量,在运行或调试程序之前进行设置。但是这里我只想运行单元测试。

有没有一种好的方法可以在不重新启动VSCode的情况下更改参数?

英文:

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?

答案1

得分: 8

你可以将以下代码片段添加到VSCode的settings.json中,以指定仅用于go test运行的环境变量:

直接定义变量:

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

或者使用专用文件(在我的示例中称为项目工作区根目录中的test.env)以MY_VAR="my value"格式,每行一个变量,包含环境变量:

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

还要注意,单元测试(顾名思义,它们测试一段代码单元)通常不应依赖于任何外部服务或资源。除了要测试的逻辑之外,应该以模拟的形式提供一切。

英文:

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.

huangapple
  • 本文由 发表于 2021年12月7日 10:21:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/70254196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定