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

15 go

我有以下示例(类似于我们在prod中所拥有的)"文本/模板"代码,它工作正常,现在我想为它创建一个单元测试,检查功能,并text/template看到我覆盖100%的代码...

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

请访问:https: //play.golang.org/p/203Al36Zigk

这是模板:

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}}
`
Run Code Online (Sandbox Code Playgroud)

Von*_*onC 3

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

为此,查看golangtext/template的源代码始终是一个好主意。

作为一个示例(根据您的情况进行调整),您src/text/template/example_test.go使用了经典的表驱动测试方法:

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
}
Run Code Online (Sandbox Code Playgroud)

对于断言部分,查看src/text/template/multi_test.go其中定义multiParseTest为带有模板的结构,*和预期结果,它允许执行如下断言

result := tmpl.Root.String()
if result != test.results[i] {
    t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.results[i])
}
Run Code Online (Sandbox Code Playgroud)