首页 > 解决方案 > 使用内容创建文件创建单元测试

问题描述

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

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

标签: unit-testinggo

解决方案


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

推荐阅读