Testing fasthttp with httptest


I am wondering how I can test an application that’s written with fasthttp using the httptest package in the base library of Go.

I found this guide which explains the testing pretty well, but the issue is that httptest does not satisfy the http.Handler interface so I have no idea how to do the http.HandlerFunc since fasthttp uses it’s own fasthttp.ListenAndServe that’s incompatible.

Any ideas on how to create a wrapper, or how to otherwise test a fasthttp written library end to end?


There are two possible approaches. Unit testing a handler isn’t really viable as you would need to create a RequestCtx and stub/mock all necessary fields.

Instead, I would unit test the code that your fasthttp handlers call out
to. I would do e2e testing of the actual handlers themselves.

There is an in memory listener implementation that you could use to avoid actually listening on a TCP port or Unix socket. You would initialise the server but serve on this listener instead of on a network connection.

You would then create a HTTP client and call the relevant methods as normal but use this listener as the transport.

If you stub/fake anything that your handlers interact with then you could make this in-memory only with no external dependencies, i.e. like a unit test but it will actually doing a full system test.

Answered By – Martin Campbell

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.