unit-testing - 用于文件创建的表驱动测试

标签 unit-testing go

我从@volker 那里得到了一个关于表驱动测试的例子,如下所示 但目前我想念我应该在真正的测试中放什么,这个测试使用字节,目前我不确定在 argsexpected []byte 中放什么, 例如我想检查文件中是否有 2 换行 然后是 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

最佳答案

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

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

关于unit-testing - 用于文件创建的表驱动测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600193/

相关文章:

parsing - 将字符串解析为映射 Golang

go - 在 Golang 中构建动态(条件)WHERE SQL 查询

java - 尽管 url 有效,Spring Controller 测试仍失败

unit-testing - 使用 CMake 在 CLion 中使用多个 Main 进行 Google 单元测试

javascript - 有没有办法控制casper的控制台输出?

python - Visual Studio 2019 找不到 python 测试(pytest 或 unittest)

c# - 对构造函数进行单元测试很重要吗?

math - 为什么 math.Pow10(e int) 返回 float64 而不是 int64?

go - 将文本输入规范化为 ASCII

go - 等待 sync.Waitgroup 延迟