创建用于内容创建文件的单元测试

时间:2018-07-30 15:03:08

标签: unit-testing go

我具有以下功能,该功能获取文件并向其中写入内容。

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. 运行代码使用此功能对其进行更新,然后对其进行解析并检查其值?有没有更好的方法来实现这种功能?

1 个答案:

答案 0 :(得分:2)

更好的方法是接受接口,例如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")
            }
        })
    }
}