gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:22:22 24 4
gpt4 key购买 nike

我从@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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com