unit-testing - 使用内容创建文件创建单元测试
问题描述
我有以下函数,它获取文件并向其中写入内容。
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)
})
}
}
这里的问题是我依赖于文件,为这种功能创建单元测试的更好方法是什么
- 在创建文件的单元测试中运行代码用这个函数更新它,然后解析它并检查值?这种功能有更好的方法吗?
解决方案
更好的方法是接受一个接口,比如io.Writer
. 在您的实际使用中,您可以传入 a *os.File
,而在您的测试中,您可以传入更容易使用的东西,例如 a 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")
}
})
}
}
推荐阅读
- docker - 为什么 Bitbucket 管道给我一个 Sass 错误,说它找不到要导入的文件或文件不可读?
- excel - 如果上面的单元格被占用,则创建 If 语句
- google-apps-script - 是否有谷歌表格方法让编码公式每天在下一个空行中填充值?
- mysql - SQL UPDATE SET SELECT 慢
- css - CSS动画向右消失并从左侧重新出现
- angular - 如何在子路径角度调用子模块
- java - orElseGet 在 Optional 的情况下如何工作
- >
- python - tesseract 图像只有数字/数字
- go - 在 wasm 构建中使用可选参数
- javascript - 如何合并多维数组?