【问题标题】:Unit test in golang with structure带有结构的golang单元测试
【发布时间】:2018-09-08 12:07:44
【问题描述】:

我使用 VSCode 生成项目的测试文件,

当前它生成以下结构

tests := []struct {
        name    string
        args    args
        wantOut ZTR
    }{
        name: "test123",
        args: args{
            ztrFile: "./testdata/ztrfile.yaml",
        },
        wantOut: “ZTR.Modules",
    }

测试应该包括 yaml 的解析和属性测试

这里调用解析文件

for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if gotOut := parseFile(tt.args.ztrFile); !reflect.DeepEqual(gotOut, tt.wantOut) {
                t.Errorf("parseFile() = %v, want %v", gotOut, tt.wantOut)
            }
        })

这是结构

type Modules struct {
    Name       string
    Type       string
    cwd       string     `yaml:”cwd,omitempty"`
}

不确定我需要在这里放什么才能使其正常工作,我尝试使用这些类型,但出现错误

        {
            name: "test123",
            args: args{
                mtaFile: "./testdata/ztrfile.yaml",
            },
            wantOut: “ZTR.Modules",
        }

我得到的错误是

message: 'cannot use "test123" (type string) as type struct { name string;参数参数; wantOut ZTR } 在数组或切片文字中' 在:'41,3' 资源: '' 代码:'未定义'

【问题讨论】:

  • 源代码的第 41 行是哪一行?
  • @Flimzy - name: "test123”, 我在 wantOut: “ZTR.Modules”, 上也出错了
  • 您缺少一些大括号。请记住,您是在在一片结构中为其提供条目

标签: go


【解决方案1】:

您的tests 声明不正确。您需要提供一片结构,但您只提供键/值:

tests := []struct {
    name    string
    args    args
    wantOut ZTR
}{
    name: "test123",
    args: args{
        mtaFile: "./testdata/ztrfile.yaml",
    },
    wantOut: “ZTR.Modules",
}

应该是:

tests := []struct {
    name    string
    args    args
    wantOut ZTR
}{
    {
        name: "test123",
        args: args{
            mtaFile: "./testdata/ztrfile.yaml",
        },
        wantOut: “ZTR.Modules",
    },
}

【讨论】:

  • 非常感谢这解决了这个问题,最后一个问题我在wantOut 中有错误,我应该放在那里?例如,如果 modules 的名称应该是 name=“just name” type=“justType”
  • 我知道这是我想要验证的 expected 但我应该怎么把它放在那里?
  • 在不知道错误是什么的情况下很难回答您的问题。
  • 如果我需要验证结构解析的输出,我应该如何把它放在那里,任何例子都会有所帮助
  • 当我输入wantOut: Modules, 时出现错误type module is not expression
猜你喜欢
  • 2013-01-04
  • 1970-01-01
  • 1970-01-01
  • 2022-11-08
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多