Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Golang-覆盖所有用例的文本/模板单元测试_Go - Fatal编程技术网

Golang-覆盖所有用例的文本/模板单元测试

Golang-覆盖所有用例的文本/模板单元测试,go,Go,我有下面的例子(类似于我们在prod中的)“text/template”代码,它工作正常,现在我想为它创建一个单元测试,检查函数和text/template,以查看我覆盖了100%的代码 这里的问题是如何进行文本/模板单元测试,它涵盖了所有案例。我目前不熟悉文本/模板,我想确保它按预期工作 请浏览: 这是模板: const tmpl = `#!/bin/bash {{- range .File.Dependency}} echo {{.EchoText}} {{- range .Install

我有下面的例子(类似于我们在prod中的)“text/template”代码,它工作正常,现在我想为它创建一个单元测试,检查函数和
text/template
,以查看我覆盖了100%的代码

这里的问题是如何进行文本/模板单元测试,它涵盖了所有案例。我目前不熟悉文本/模板,我想确保它按预期工作

请浏览:

这是模板:

const tmpl = `#!/bin/bash
{{- range .File.Dependency}}
echo {{.EchoText}}
{{- range .Install}}
submitting {{.name}}
{{- end}}
{{.TypeCommand}}
{{end}}

{{- range $k, $v := .API}}
echo {{$k}}
submitting {{$v}}
{{end}}
`

您应该设置一个模板测试文件,专用于测试模板文件的输出

为此,查看数据源始终是一个好主意

例如(根据您的情况进行调整),您有一个使用经典方法的:

package template_test

import (
    "log"
    "os"
    "strings"
    "text/template"
)

func ExampleTemplate() {
    // Define a template.
    const letter = `
Dear {{.Name}},
{{if .Attended}}
It was a pleasure to see you at the wedding.
{{- else}}
It is a shame you couldn't make it to the wedding.
{{- end}}
{{with .Gift -}}
Thank you for the lovely {{.}}.
{{end}}
Best wishes,
Josie
`

    // Prepare some data to insert into the template.
    type Recipient struct {
        Name, Gift string
        Attended   bool
    }
    var recipients = []Recipient{
        {"Aunt Mildred", "bone china tea set", true},
        {"Uncle John", "moleskin pants", false},
        {"Cousin Rodney", "", false},
    }

    // Create a new template and parse the letter into it.
    t := template.Must(template.New("letter").Parse(letter))

    // Execute the template for each recipient.
    for _, r := range recipients {
        err := t.Execute(os.Stdout, r)
        if err != nil {
            log.Println("executing template:", err)
        }
    }

    // Output:
    // Dear Aunt Mildred,
    //
    // It was a pleasure to see you at the wedding.
    // Thank you for the lovely bone china tea set.
    //
    // Best wishes,
    // Josie
    //
    // Dear Uncle John,
    //
    // It is a shame you couldn't make it to the wedding.
    // Thank you for the lovely moleskin pants.
    //
    // Best wishes,
    // Josie
    //
    // Dear Cousin Rodney,
    //
    // It is a shame you couldn't make it to the wedding.
    //
    // Best wishes,
    // Josie
}
对于断言部分,请查看其中定义为带模板的结构*和预期结果,该结果允许执行以下操作:

yourcodefile.go

    type API map[string]string

    type data struct {
        File *File
        API  API
    }
    func DynamicdataForTemplate() data {
                    f := new(File)
                    f.Dependency = []Dependency{{
                        Name:    "ui",
                        Type:    "runner",
                        CWD:     "/ui",
                        Install: []Install{{"name": "api"}},
                    }, {
                        Name:    "ui2",
                        Type:    "runner2",
                        CWD:     "/ui2",
                        Install: []Install{{"name": "api2"}},
                    }}

                    datav := data{}
                    datav.File = f
                    datav.API = API{"runner3": "api3", "runner4": "api4"}

                    return datav
                }

 func ParseTemplate() error {
                    parsedTempl, err := template.New("t").Parse(tmpl)
                    err = parsedTempl.Execute(os.Stdout, DynamicdataForTemplate())
                    return err
}

    func main() {
        _ = ParseTemplate()
    }

使用此断言包编写测试用例

yourcodefile\u test.go

import (
    "testify/assert"
    "testing"
)


func TestDynamicdataForTemplate(t *testing.T) {
    t.Run("should return the Type", func(t *testing.T) {
        dataType := data{}
        assert.IsType(t, dataType, DynamicdataForTemplate())
    })
}

func TestParseTemplate(t *testing.T) {
    t.Run("should return the nil", func(t *testing.T) {
        assert.Nil(t, ParseTemplate())
    })
}

代码覆盖率报告命令

go test -coverprofile=coverage.out
go tool cover -html=coverage.out

谢谢:),我不确定我是否完全理解它,我应该如何做断言?您能在我的上下文中提供示例还是关闭?@Ninawatcher是的,该测试只涉及执行,而不涉及检查模板输出的断言。我对答案进行了编辑,添加了一个执行这种断言的示例。同样,这与中描述的hat非常相似:输入和输出列表,断言检查您的程序从列表中交付预期的输出。我完全忘记了示例是用
go test
Hi运行的,我没有太多时间来测试它,现在我想测试它。因为我们的时间(赏金)不多了。你能帮忙吗?假设文件逻辑在file
genfile.go
中,我已经创建了file
genfile\u test.go
,你能举个例子吗?因为如果我使用
func TestGenerate(t*testing.t){result:=tmpl.Root.String(),如果result!=test.results[I]{t.Errorf(%s=(%q):获取\n\t%v\n预期\n\t%v“,test.name,test.input,result,test.results[i])}
它不工作…->对于测试,请使用此软件包。谢谢您的回答!,请您详细说明我应该如何检查真实模板,这里您正在检查数据类型,这是正常的,但还不够……如果我传递了错误的参数/数据,我需要检查模板的行为是否正常。谢谢您需要伪造
输入
go test -coverprofile=coverage.out
go tool cover -html=coverage.out