Unit testing your first WebSocket server
Unit testing or test-driven development helps the developer to design loosely-coupled code with the focus on code reusability. It also helps us to realize when to stop coding and make changes quickly.
In this recipe, we will learn how to write a unit test for the WebSocket server that we have already written in one of our previous recipes.
Note
See the Creating your first WebSocket server recipe.
How to do it…
- Install the
github.com/gorilla/websocket
andgithub.com/stretchr/testify/assert
packages using thego get
command, as follows:
$ go get github.com/gorilla/websocket $ go get github.com/stretchr/testify/assert
- Create
websocket-server_test.go
where we will create a test server, connect to it using the Gorilla client, and eventually read and write messages to test the connection, as follows:
package main import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" ) func TestWebSocketServer...