登录
首页 >  Golang >  Go问答

文件创建的表驱动测试方案

来源:stackoverflow

时间:2024-03-24 09:27:25 424浏览 收藏

**文件创建的表驱动测试方案** 在表驱动测试中,测试用例以表的形式组织,其中每一行代表一个测试用例。对于文件创建测试,该表可以包含以下列: * **名称:**测试用例的名称 * **参数:**传递给被测函数的参数 * **预期结果:**被测函数的预期输出

问题内容

我从@volker那里得到了一个关于表驱动测试的例子,如下所示 但目前我错过了我应该在真正的测试中放入什么,这个测试使用的是字节,目前我不确定在 argsexpected []byte 中放入什么, 例如我想检查文件中是否有 2 new lineapplication 条目,如何在不需要创建真实文件并解析它的情况下执行此操作?

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


解决方案


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

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)
    }
}

到这里,我们也就讲完了《文件创建的表驱动测试方案》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>