Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Uday Yadav
Uday Yadav

Posted on

     

Testing simple web server

Testing web server in Golang

  • create a file with name<anything>_test.go, these files are ignore by compiler
  • write a func matchingfunc TestXxx(*testing.T) where Xxx does not start with a lowercase letter. The function name serves to identify the test routine.
  • to run the test :go test

Testing

  • inorder to test the handler, we call it by passinghttp.ResponseWriter and*http.Request

  • to create a new Request

req, err := http.NewRequest(    http.MethodGet,                 // defining method of HTTP request    "http://localhost:8080/",       // Url to hit    nil,                            // Body (taking nil right now))// checking for any errors            if err != nil {    t.Fatalf("Could not create a request %v", err)}
Enter fullscreen modeExit fullscreen mode
  • to record the response from the writer
rec := httptest.NewRecorder()
Enter fullscreen modeExit fullscreen mode
  • to verify
// calling the functionhelloWorldEndPoint(rec, req)// checking status codeif rec.Code != http.StatusOK {    t.Errorf("accepted status 200, got %v", rec.Code)}// checking the msg returnedif !strings.Contains(rec.Body.String(), "hello world") {    t.Errorf("unexpected body in response %q", rec.Body.String())}
Enter fullscreen modeExit fullscreen mode

Full code server.go

package mainimport (    "fmt"    "log"    "net/http")func main() {    http.HandleFunc("/", helloWorldEndPoint)    fmt.Println("Server :  http://localhost:8080")    log.Fatal(http.ListenAndServe(":8080", nil))}func helloWorldEndPoint(writer http.ResponseWriter, request *http.Request) {    fmt.Fprintf(writer, "hello world")}
Enter fullscreen modeExit fullscreen mode

full code main_test.go

package mainimport (    "net/http"    "net/http/httptest"    "strings"    "testing")func TestHandler(t *testing.T) {    req, err := http.NewRequest(        http.MethodGet,        "http://localhost:8080/",        nil,    )    if err != nil {        t.Fatalf("Could not create a request %v", err)    }    rec := httptest.NewRecorder()    helloWorldEndPoint(rec, req)    if rec.Code != http.StatusOK {        t.Errorf("accepted status 200, got %v", rec.Code)    }    if !strings.Contains(rec.Body.String(), "hello world") {        t.Errorf("unexpected body in response %q", rec.Body.String())    }}
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Engineer
  • Location
    New Delhi
  • Work
    Student at GGSIPU
  • Joined

More fromUday Yadav

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp