gpt4 book ai didi

unit-testing - 为包含内容的文件创建创建单元测试

转载 作者:IT王子 更新时间:2023-10-29 02:01:37 29 4
gpt4 key购买 nike

我有以下获取文件并向其写入内容的函数。

func setFile(file *os.File, appStr models.App) {

file.WriteString("1.0")

file.WriteString("Created-By: application generation process")
for _, mod := range appStr.Modules {

file.WriteString(NEW_LINE)
file.WriteString(NEW_LINE)
file.WriteString("Application")
file.WriteString(NEW_LINE)
file.WriteString("ApplicationContent")
file.WriteString(NEW_LINE)
file.WriteString("ContentType")

}
}

为此,我生成了如下单元测试

func Test_setFile(t *testing.T) {


type args struct {
file *os.File
appStr models.App
}
var tests []struct {
name string
args args
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setFile(tt.args.file, tt.args.AppStr)
})
}
}

这里的问题是我依赖于文件,为这种功能创建单元测试的更好方法是什么

  1. 在创建文件的单元测试中运行代码,用这个函数更新它,然后解析它并检查值?这种功能有更好的方法吗?

最佳答案

更好的方法是接受一个接口(interface),比如io.Writer。在您的实际使用中,您可以传入 *os.File,而在您的测试中,您可以传入更易于使用的内容,例如 bytes.Buffer

类似的东西(未经测试但应该让你开始):

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

fmt.Fprint(file, "Created-By: application generation process")
for _, mod := range appStr.Modules {
fmt.Fprint(file, NEW_LINE)
fmt.Fprint(file, NEW_LINE)
fmt.Fprint(file, "Application")
fmt.Fprint(file, NEW_LINE)
fmt.Fprint(file, "ApplicationContent")
fmt.Fprint(file, NEW_LINE)
fmt.Fprint(file, "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")
}
})
}
}

关于unit-testing - 为包含内容的文件创建创建单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51596953/

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