Skip to content

Instantly share code, notes, and snippets.

@justinas
Created August 17, 2014 20:17
Show Gist options
  • Save justinas/b92fb2dcd1964a4bbb41 to your computer and use it in GitHub Desktop.
Save justinas/b92fb2dcd1964a4bbb41 to your computer and use it in GitHub Desktop.
An idea for Go template mocking/output recording
/*
Basically, while writing a web app in Go I felt that
templates were the most undertested part of it.
I have no checks whether a handler actually executes a template,
is it the right one, is the correct context passed, etc.
This kind of mock provides a way to make lots of these checks.
*/
type Executable interface{
Execute(wr io.Writer, data interface{}) error
ExecuteTemplate(wr io.Writer, name string, data interface{}) error
}
// Your template map (instead of map[string]*template.Template)
// html/template or text/template templates satisfy Executable automatically.
var templates map[string]Executable
// This wraps the real template
type TemplateMock struct {
*template.Template
// some private fields
}
// Satisfies Executable
func (t *TemplateMock) Execute(wr io.Writer, data interface{}) error
func (t *TemplateMock) ExecuteTemplate(wr io.Writer, name string, data interface{}) error
// But has benefits for testing, like:
func (t *TemplateMock) TimesRendered() int
func (t *TemplateMock) Output() []byte
func (t *TemplateMock) ContextReceived() interface{}
// Probably some more.
// In production
templates["index.html"] = template.ParseFiles(...)
// In tests
templates["index.html"] = &TemplateMock{template.ParseFiles(...)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment