API Testing In Golang

11,050

Solution 1

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
}

Solution 2

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)
Share:
11,050

Related videos on Youtube

Spikey
Author by

Spikey

Updated on June 01, 2022

Comments

  • Spikey
    Spikey almost 2 years

    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.

  • Spikey
    Spikey over 7 years
    Niko - it sounds like you are saying that the Golang built-in testing package is sufficient/robust/and easy enough for all types of tests and that I have no use in looking at any other solutions?
  • daplho
    daplho over 7 years
    Yes - it has worked well for me as far as API testing is concerned.
  • Renra
    Renra over 5 years
    Testing handlers is fine, but that does not test that the handlers are actually used by the final application, nor does it test that the routing works well.
  • Marcello Romani
    Marcello Romani about 5 years
    While I found this answer interesting, I'd argue that testing the handler can be conveniently bypassed by structuring the API-called code in so that the handler itself is just a very tiny integration layer. The actual code will be unit tested the usual way.
  • NlaakALD
    NlaakALD over 4 years
    Link is invalid
  • Cyro Dubeux
    Cyro Dubeux over 4 years
    Link fixed. You can access now.