在 VSCode 中使用命令行参数调试 Go 测试

Debugging Go tests with command line arguments in VSCode

我需要在 Go 中构建一个在执行时接受一些命令行参数的测试用例。

测试文件看起来很普通:

package somelogic_test

import (
    sl "example.com/somelogic"
    "flag"
    "testing"
)

func TestSomeLogic(t *testing.T) {
    flag.Parse()
    strSlice := flag.Args()
    sl.SomeLogic(strSlice)
}

当我 运行 测试为 go test -v somelogic_test.go -args arg1 arg2 arg3 时,它像魅力一样工作,接受 arg1、arg2、arg3 作为字符串片段并将其传递给 SomeLogic 函数。到目前为止,还不错。

现在我想调试 VSCode 中的执行。我发现 this link 建议将所有命令行参数放在 launch.json 文件的“args”字段中。所以我按照建议做了,我的 launch.json 配置现在看起来如下:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch file",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${fileDirname}",
            "env": {},
            "args": ["-v","somelogic_test.go","-args","arg1","arg2","arg3"]
        }
    ]
}

但是,这根本不起作用,因为当我在 运行 测试和调试测试模式下 运行 somelogic_test.go 时,flag.Parse()flag.Args(),结果 strSlice 只是一个空切片。

请建议如何修改 launch.json 以便 flag.Parse() 接受命令行参数并可用于进一步调试?

参考go help testflag:

The 'go test' command takes both flags that apply to 'go test' itself and flags that apply to the resulting test binary.

你需要区分这两种标志,因为在 VSCode 中使用 Go 扩展调试测试时,它会先编译测试二进制文件,然后将参数传递给它。在您的 go test 命令行中,-v somelogic_test.go 应该是 go test 本身的标志,arg1 arg2 arg3 应该是生成的测试二进制文件的标志,不是吗?

试试这个,它在我的环境中有效:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Test file",
            "type": "go",
            "request": "launch",
            "mode": "test",
            // Indicate the target here
            "program": "${fileDirname}/somelogic_test.go",
            // or just use "The current opened file"
            // "program": "${file}", 
            "env": {},
            "args": ["-test.v", "--", "arg1","arg2","arg3"]
        }
    ]
}

However, this does not work at all, cause when I run somelogic_test.go both in Run Test and Debug Test modes no arguments are accepted with flag.Parse() and flag.Args(), and as a result strSlice is just an empty slice.

注意上面出现的run testdebug test按钮测试功能不要使用launch.json。转到 Run and debug 边栏以启动您设置的特定配置。