Skip to content
/ wstest Public

go websocket client for unit testing of a websocket handler


Notifications You must be signed in to change notification settings


Folders and files

Last commit message
Last commit date

Latest commit



63 Commits

Repository files navigation


Build Status codecov GoDoc Go Report Card

A websocket client for unit-testing a websocket server

The gorilla organization provides full featured websocket implementation that the standard library lacks.

The standard library provides a httptest.ResponseRecorder struct that test an http.Handler without ListenAndServe, but is helpless when the connection is being hijacked by an http upgrader. As for testing websockets, it has the httptest.NewServer that actually listens on a socket on an arbitrary port.

This package provides a NewDialer function to test just the http.Handler that upgrades the connection to a websocket session. It runs the handler function in a goroutine without listening on any port. The returned websocket.Dialer then can be used to dial and communicate with the given handler.


go get -u


See the example test.

An example how to modify a test function from using httptest.Server to use wstest.NewDialer function.

func TestHandler(t *testing.T) {
	var err error

	h := &myHandler{}
-	s := httptest.NewServer(h)
-	defer s.Close()
-	d := websocket.Dialer{}
+	d := wstest.NewDialer(h)

-	c, resp, err := d.Dial("ws://" + s.Listener.Addr().String() + "/ws", nil)
+	c, resp, err := d.Dial("ws://" + "whatever" + "/ws", nil)
	if err != nil {
	if got, want := resp.StatusCode, http.StatusSwitchingProtocols; got != want {
		t.Errorf("resp.StatusCode = %q, want %q", got, want)
	err = c.WriteJSON("test")
	if err != nil {