package main import ( "bytes" "io" "io/ioutil" "net/http" "net/http/httptest" "os/exec" "strings" "testing" ) func Test_routing(t *testing.T) { ts := httptest.NewServer(NewRouter()) defer ts.Close() aBook := `{"Title": "Gophers Invation in Sweden"}` cases := []struct { method, path string body io.Reader expCode int expBodyContain string expContentType string }{ {"GET", "/books", nil, 200, "books", "application/json"}, {"POST", "/books", nil, 400, "", ""}, {"POST", "/books", bytes.NewBufferString(aBook), 201, "", ""}, } for _, c := range cases { resp := mustRequest(t, c.method, ts.URL+c.path, c.body) if resp.StatusCode != c.expCode { t.Error(resp.StatusCode, c.expCode) } gotContentType := resp.Header.Get("Content-Type") if gotContentType != c.expContentType { t.Error(gotContentType, c.expContentType) } body, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatal(err) } if strings.Index(string(body), c.expBodyContain) < 0 { t.Error(string(body), "\nmissing\n", c.expBodyContain) } } } func mustRequest(t *testing.T, method, path string, body io.Reader) *http.Response { t.Helper() req, err := http.NewRequest(method, path, body) if err != nil { t.Fatal(err) } resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } return resp } func Test_build_and_start(t *testing.T) { out, err := exec.Command(GOBINARY, "build").CombinedOutput() if err != nil { t.Fatal(err, string(out)) } cmd := exec.Command("./app") err = cmd.Start() if err != nil { t.Fatal(err) } err = cmd.Process.Kill() if err != nil { t.Fatal(err) } }