Testing your REST api in Go with forest
Go package forest was created to simplify the code needed to write real tests of a REST api. Such tests need to setup Http Requests, send them and inspect Http Responses. The Go standard library has all that is needed to achieve this flow but the required amount of code, especially the error handling, makes tests harder to read and longer to write.
Testing github
Let's create a few tests that examine the response of the public github API call.
package main
import (
"net/http"
"testing"
. "github.com/emicklei/forest"
)
var github = NewClient("https://api.github.com", new(http.Client))
func TestForestProjectExists(t *testing.T) {
cfg := NewConfig("/repos/emicklei/{repo}", "forest").Header("Accept", "application/json")
r := github.GET(t, cfg)
ExpectStatus(t, r, 200)
}
The package variable github (line 10) is a forest Http client wrapper and provides the api to send Http requests (such as GET). On line 13, the cfg variable is a RequestConfig value that is used to build a http.Request with method,url,headers,body. The variable r is a *http.Response. The ExpectStatus function checks the status code. If the code does not match, then the following will be reported.