DEV Community

林子篆
林子篆

Posted on • Originally published at dannypsnl.github.io on

Use httpexpect to test server

Use built-in functionality to test a Go server is a painful experience. The problem is because we have to handle too many errors and get so much thing we don't always need.

Of course, we will create an abstraction to reduce this panic. But if we already have a mature solution? That is httpexpect

We have two options for import:

  • import "github.com/gavv/httpexpect.v1"
  • import "github.com/gavv/httpexpect"

The different is v1 is stable branch, another is master branch on GitHub.

I suggest pick stable one for the company project, but it’s fine to use master branch at side project.

httpexpect works pretty good with httptest. A simple example:

type fakeHandler struct {
}

func (h *fakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello")
}

func TestIt(t *testing.T) {
    handler := &fakeHandler{}
    server := httptest.NewServer(handler)
    defer server.Close()

    e := httpexpect.New(t, server.URL)

    e.GET("/").
        Expect().
        Status(http.StatusOK).
        Body().Equal("Hello")
}

Enter fullscreen mode Exit fullscreen mode

How about add form value?

e.PATCH("/test/patch").WithFormField("value", "patch").
    Expect().Status(http.StatusOK).
    Body().Equal("patch")

Enter fullscreen mode Exit fullscreen mode

JSON response?

e.POST("/post").
    Expect().Status(http.StatusOK).
    ContentType("application/json", "").
    JSON().Equal(expected)

Enter fullscreen mode Exit fullscreen mode

Query?

e.GET("/user").WithQuery("name", "Danny").
    Expect().Status(http.StatusOK).

Enter fullscreen mode Exit fullscreen mode

Hope you would feel happy with this little introduction.

Discussion (0)