登录
首页 >  Golang >  Go问答

编写测试用例以验证文件内容

来源:stackoverflow

时间:2024-03-12 13:42:24 261浏览 收藏

golang学习网今天将给大家带来《编写测试用例以验证文件内容》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

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

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

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

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

解决方案


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

到这里,我们也就讲完了《编写测试用例以验证文件内容》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>