7

I am developing a REST API based on Gin Go, the endpoint looks something like below:

func carsByType(c *gin.Context) {
    fmt.Println("Go Request in Handler...")
    carType := c.Params.ByName("type")
    fmt.Println(carType)
    if carType != "" {

    }
    c.JSON(http.StatusBadRequest, gin.H{"result": "Bad request"})
    return
}

func main() {
    router := gin.Default()
    router.GET("/cars/:type", carsByType)
    router.Run(":80")
}

When I am making request to the endpoint via browser and cURL its just working fine, getting the carType value but when I am running the tests its returning bad request and getting carType is "".

For testing the endpoint my test code looks like this:

func TestGetcarsByType(t *testing.T) {
    gin.SetMode(gin.TestMode)
    handler := carsByType
    router := gin.Default()
    router.GET("/cars/1", handler)

    req, err := http.NewRequest("GET", "/cars/1", nil)
    if err != nil {
        fmt.Println(err)
    }
    resp := httptest.NewRecorder()
    router.ServeHTTP(resp, req)
    assert.Equal(t, resp.Code, 200)
}       

What am I doing wrong?

1
  • router.GET("/cars/1", handler) should be router.GET("/cars/:type", handler) in your test. Commented Mar 14, 2016 at 15:23

1 Answer 1

9

router.GET("/cars/1", handler) should be router.GET("/cars/:type", handler) in your test.

Note that a better (more testable; less duplication of routes) would be to create a SetupRouter() *gin.Engine function that returns all of your routes. e.g.

// package main

// server.go
// This is where you create a gin.Default() and add routes to it
func SetupRouter() *gin.Engine {
    router := gin.Default()
    router.GET("/cars/:type", carsByType)

    return router
}

func main() {
    router := SetupRouter() 
    router.Run()
}

// router_test.go
testRouter := SetupRouter()

req, err := http.NewRequest("GET", "/cars/1", nil)
if err != nil {
    fmt.Println(err)
}

resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
assert.Equal(t, resp.Code, 200)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.