创建单元测试以使用内容创建文件

I've the following function which getting a file and write content to it.

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

    }
}

For that I generate a unit test like following

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

The problem here is that im depending on file, what is better approach to create unit test for this kind of function

  1. run code in the unit test which is creating file update it with this function and then parse it and check the values ? is there a better approach for this kind of function ?

The better approach would be to accept an interface, something like io.Writer. In your real usage you can pass in a *os.File, and in your tests you can pass in something easier to work with like a bytes.Buffer.

Something like (untested but should get you started):

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