How to perform testing for a text template

hey guys, i need to do a testing for a text template that checks whether

  • arguments passed or not
  • arguments passed are valid type

I’m using nested Structs to populate values to template

This is the template
`package templates

//ConfigMapJSON variable containing configmap json
const ConfigMapJSON = { "apiVersion": "v1", "kind": "ConfigMap", "metadata": { "name": "{{.Name}}", "namespace": "{{.Namespace}}" }, "data": { "DB_HOST": "{{.DBHost}}", "DB_NAME": "{{.DBName}}", "ENV": "{{.ENV}}", "GIT_BRANCH_NAME": "{{.GitBranch}}", "INSTANCE_ENV": "{{.InstanceENV}}", "S3_BUCKET": "{{.S3Bucket}}", "S3_DOMAIN": "{{.S3Domain}}", "S3_REGION": "{{.S3Region}}", "SIMPLESAMLPHP_CONFIG_DIR": "{{.ConfigDir}}" } }

Struct i’m using
//ConfigMaps struct
type ConfigMaps struct {
Name string json:"name"
Namespace string json:"namespace"
DBHost string json:"dbhost"
DBName string json:"dbname"
ENV string json:"env"
GitBranch string json:"gitbranch"
InstanceENV string json:"instanceenv"
S3Bucket string json:"s3bucket"
S3Domain string json:"s3domain"
S3Region string json:"s3region"
ConfigDir string json:"configdir"

controller for excecuting template

`//ConfigMapController function
func ConfigMapController(val []byte) string {
var standardLogger = li.NewLogger()

tmpl, err := template.New("configMap-tmpl").Parse(templates.ConfigMapJSON)
if err != nil {
err = json.Unmarshal(val, &configMap)
if err != nil {
var temp bytes.Buffer
err = tmpl.Execute(&temp, configMap)
if err != nil {
result := temp.String()
return result

Any help is much appreciated thank you.


I’d suggest not using a template at all for this, but declaring a struct that you then json.Marshal instead. Advantages with that:

  • You don’t need to worry about arguments having the wrong type, because they can’t, because the struct fields will be strongly typed
  • You don’t need to worry about generating broken JSON because the template is bad

Validating the struct fields for correctness before marshalling will also be a lot easier than validating the template output.


Thanks for replying,
yeah i agree with you for using structs instead of templates, because i used struct before and testing works fine.
But what if i had to use templates?


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.