Go Martini Unit Test Example

405 views Asked by At

I'm very new to Go and was wondering is there any convention/standard with examples on how to test Go Martini's Handler code?

Thanking you in advance!

1

There are 1 answers

0
elithrar On

The martini-contrib library has a lot of existing code worth looking at: https://github.com/martini-contrib/secure/blob/master/secure_test.go

e.g.

func Test_No_Config(t *testing.T) {
    m := martini.Classic()
    m.Use(Secure(Options{
    // nothing here to configure
    }))

    m.Get("/foo", func() string {
        return "bar"
    })

    res := httptest.NewRecorder()
    req, _ := http.NewRequest("GET", "/foo", nil)

    m.ServeHTTP(res, req)

    expect(t, res.Code, http.StatusOK)
    expect(t, res.Body.String(), `bar`)
}

To sum:

  1. Create a server with martini.Classic()
  2. Create a route to the handler you want to test
  3. Execute it against a response recorder
  4. Inspect the results (status code, body) on the response recorder are as expected.