Created
August 17, 2014 20:17
-
-
Save justinas/b92fb2dcd1964a4bbb41 to your computer and use it in GitHub Desktop.
An idea for Go template mocking/output recording
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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