1

I have written test case to test method in Gin-Gonic framework but it in not giving expected output while running test case. But when I run method using API in Postman it is working properly.

Test case

func TestList(t *testing.T) {
    router := gin.New()
    router.GET("/testList", things.List)
    req, _ := http.NewRequest("GET", "/stuff", nil)
    resp := httptest.NewRecorder()
    router.ServeHTTP(resp, req)
    assert.NotNil(t, resp.Body.String())
    assert.Equal(t, 201,resp.Code, resp.Body.String())
}

Method on which test case created

func List(c *gin.Context) {
    db := c.MustGet("db").(*mgo.Database)
    things := []models.Thing{}
    err := db.C(models.CollectionStuff).Find(nil).All(&things)
    if err != nil {
        c.Error(err)
    }
    c.JSON(http.StatusOK, things)
}

Router

func main() {
    router := gin.Default()
    router.Use(middlewares.Connect)
    router.GET(Prefix +"/things", things.List)
}

When I run test case using go test -v ./... Output

 Error Trace:    thing_test.go:31
 Error:          Not equal:
 expected: 201
 actual  : 404
 Test: TestList
 Messages: 404 page not found

While running through API it works but not while running through test case.

Amit Upa
  • 307
  • 1
  • 2
  • 13
  • 1
    A router is used for routing, ie. given a request the router decides which handler to execute. In your test you registered the `things.List` handler under `/testList` and created a request with the url path `/stuff`. Why would you expect anything other than `404`? The router in your test and the router in your `main` are completely different, one has middleware the other doesn't, one registers the handler under `Prefix + /things` the other under `/testList` it is only logical that the test doesn't produce the same output as when you run the program normally sending requests with postman. – mkopriva Jun 10 '19 at 21:36
  • 1
    ... also note that `http.StatusOK` is `200` not `201`, even if you did everything else ok your test would still fail because 200 != 201. – mkopriva Jun 10 '19 at 21:43

0 Answers0