Created
May 22, 2016 14:41
-
-
Save Integralist/cf76668bc46d75058ab5f566d96ce74a to your computer and use it in GitHub Desktop.
Testing Go Web Applications http://www.meetspaceapp.com/2016/05/16/acceptance-testing-go-webapps-with-cookies.html
This file contains hidden or 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
// package main is used here just for ease of running the demo. | |
// In reality, this would be package app | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
// App is our Application's base http.Handler | |
type App struct { | |
*http.ServeMux | |
} | |
// NewApp constructs a new App and initializes our routing | |
func NewApp() *App { | |
mux := http.NewServeMux() | |
app := &App{mux} | |
mux.HandleFunc("/", app.Root) | |
return app | |
} | |
// Root is the root page of our application | |
func (a *App) Root(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprint(w, "Hello!") | |
} | |
var port = flag.Int("port", 8080, "Port to serve on") | |
func main() { | |
flag.Parse() | |
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), NewApp())) | |
} |
This file contains hidden or 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
func TestAppRoot(t *testing.T) { | |
app := NewApp() | |
server := httptest.NewServer(app) | |
defer server.Close() | |
resp, err := http.Get(server.URL + "/") | |
if err != nil { | |
t.Error(err) | |
} | |
buf := &bytes.Buffer{} | |
buf.ReadFrom(resp.Body) | |
if strings.Index(buf.String(), "Hello!") == -1 { | |
t.Error("Root should say hello") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment