小编典典

表驱动的文件创建测试

go

我从@volker得到了一个有关表驱动测试的示例,如下所示,但是目前我错过了我应该在真实测试中放入的内容,该测试使用的是字节,目前我不确定在args和中放入什么expected []byte,例如,我想检查一下在文件中2 new line然后是application条目,我该如何做而无需创建真实文件并进行解析?

type Models struct {
    name        string
    vtype       string
    contentType string
}

func setFile(file io.Writer, appStr Models) {
    fmt.Fprint(file, "1.0")

    fmt.Fprint(file, "Created-By: application generation process")
    for _, mod := range appStr.Modules {
        fmt.Fprint(file, "\n")
        fmt.Fprint(file, "\n")
        fmt.Fprint(file,  appStr.vtype) //"userApp"
        fmt.Fprint(file, "\n")
        fmt.Fprint(file, appStr.name) //"applicationValue"
        fmt.Fprint(file, "\n")
        fmt.Fprint(file, appStr.contentType)//"ContentType"
    }
}

func Test_setFile(t *testing.T) {
    type args struct {
        appStr models.App
    }
    var tests []struct {
        name string
        args args
        expected []byte
   }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            b := &bytes.Buffer{}
            setFile(b, tt.args.AppStr)
            if !bytes.Equal(b.Bytes(), tt.expected) {
                t.Error("somewhat bad happen")
            }
        })
    }
}

我阅读并理解了以下示例,但不了解字节和文件 https://medium.com/@virup/how-to-write-concise-tests-
table-driven-tests-ed672c502ae4


阅读 243

收藏
2020-07-02

共1个答案

小编典典

如果一开始只检查静态内容,那么您实际上只需要进行一项测试。它看起来像这样:

func Test_setFile(t *testing.T) {
    type args struct {
        appStr models.App
    }
    var tests []struct {
        name string
        args args
        expected []byte
    }{
        name: 'Test Static Content',
        args: args{appStr: 'Some String'},
        expected: []byte(fmt.Sprintf("%s%s%s", NEW_LINE, NEW_LINE, "Application")),
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            b := &bytes.Buffer{}
            setFile(b, tt.args.AppStr)
            if !bytes.Equal(b.Bytes(), tt.expected) {
                t.Error("somewhat bad happen")
            }
        })
    }
}

尽管由于该测试只有一个案例,所以这里实际上不需要使用表驱动的测试。您可以清理它看起来像这样:

func Test_setFile(t *testing.T) {
    b := &bytes.Buffer{}
    setFile(b, 'Some String')
    want := []byte(fmt.Sprintf("%s%s%s", NEW_LINE, NEW_LINE, "Application"))
    got := b.Bytes()
    if !bytes.Equal(want, got) {
        t.Errorf("want: %s got: %s", want, got)
    }
}
2020-07-02