Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API Testing In Golang

I know that Golang has a testing package that allows for running unit tests. This seems to work well for internally calling Golang functions for unit tests but it seems that some people were trying to adapt it for API testing as well.

Given to the great flexibility of automated testing frameworks like Node.js' Mocha with the Chai assertion library, for what kind of tests does it make sense to use Golang's testing package vs. something else?

Thanks.

like image 918
Spikey Avatar asked Feb 07 '17 13:02

Spikey


2 Answers

I agree with the comment by @eduncan911. More specifically you can design your API with testing in mind by making sure that your handlers accept an

http.ResponseWriter

as a parameter in addition to the appropriate request. At that point you will be set to declare a new request:

req, err := http.NewRequest("GET", "http://example.com", nil)

as well as a new httptest recorder:

recorder := httptest.NewRecorder()

and then issue the new test request to your handler:

yourHandler(recorder, req)

so that you can finally check for errors/etc. in the recorder:

if recorder.Code != 200 {
  //do something
}
like image 120
daplho Avatar answered Nov 03 '22 13:11

daplho


For making a dummy request, you have to first initialise the router and then set the server and after that make request. Steps to be follow:

1. router := mux.NewRouter() //initialise the router
2. testServer := httptest.NewServer(router) //setup the testing server
3. request,error := http.NewRequest("METHOD","URL",Body)
4. // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
        resp := httptest.NewRecorder()
5. handler := http.HandlerFunc(functionname)
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
        handler.ServeHTTP(resp, req)
like image 2
Nikta Jn Avatar answered Nov 03 '22 15:11

Nikta Jn