我需要在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作为字符串片段,并将其传递给某个逻辑函数.到目前为止,一切顺利.

现在我想在VSCode中调试执行.我找到了this link个建议将所有命令行参数放在emits 的"args"字段中.json文件.所以我按照建议做了,我的发布.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"]
        }
    ]
}

然而,这根本不起作用,因为当我运行一些逻辑测试时.在运行测试和调试测试模式下,flag.Parse()flag.Args()都不接受任何参数,因此strSlice只是一个空片段.

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

推荐答案

参见go help testflag:

"go test"命令接受应用于"go test"本身的两个标志

您需要区分这两种标志,因为当使用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"]
        }
    ]
}

然而,这根本不起作用,因为当我运行一些逻辑测试时.go

请注意,测试功能上方出现的run testdebug test按钮不使用launch.json.转到Run and debug侧栏启动您设置的特定配置.

Go相关问答推荐

使用Golang的Lambda自定义al2运行时,初始化阶段超时

Golang SDK for DynamoDB:ReturnValuesOnConditionCheckFailure在条件chcek失败发生时不返回条件的详细信息

Redis:尽管数据存在,但 rdb.Pipelined 中出现redis:nil错误

如何从 nil 指针创建值

死锁 - 所有 goroutine 都处于睡眠状态(即使使用等待组)

以编程方式取消 pyspark dataproc 批处理作业(job)

Exchange Web 服务 - 使用 soap xml 请求查找所有未读邮件

具有嵌套重复的正则表达式

SSH 代理,数据包长度错误

如何在golang中按字符a对字符串数组进行排序

为什么 Go 被认为是部分抢占式的?

每次有人进入我的网站时如何运行特定功能?

如何使用 math/big 对 bigInt 进行取模?

即使一个测试用例失败,如何运行所有测试用例

GoReleaser 和 ssh-agent Github 操作:为什么无法读取用户名...终端提示已禁用?

具有相同提前返回语句的函数的不同基准测试结果

Go模板中的浮点除法

如何访问Go 1.18泛型 struct (structs)中的共享字段

我应该明确地创建一个与Belongs To或Has Many对称的关系吗?

有没有办法停止long blocking 函数?