gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:43:43 26 4
gpt4 key购买 nike

我需要在 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 运行测试时,它像 charm 一样工作,接受 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 只是一个空 slice 。

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

最佳答案

引用go help testflag:

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

您需要区分这两种标志,因为在带有 Go 扩展的 VSCode 中调试测试时,它会先编译测试二进制文件,然后将参数传递给它。在你的 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.goboth in Run Test and Debug Test modes no arguments are accepted withflag.Parse() and flag.Args(), and as a result strSlice is just anempty slice.

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

关于go - 在 VSCode 中使用命令行参数调试 Go 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71767280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com