Programmatically set an url parameter in gin context for testing purpose

8.8k views Asked by At

I am writing some test suites for gin middlewares. I found a solution to test them without having to run a full router engine, by creating a gin context like this :

w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

The goal is to test my function by calling :

MyMiddleware(c)

// Then I use c.MustGet() to check if every expected parameter has been transmitted to gin
// context, with correct values.

One of my middlewares relies on c.Param(). Is it possible to programatically set an Url param in gin (something like c.SetParam(key, value)) before calling the middleware ? This is only for test purpose so I don't mind non-optimized solutions.

3

There are 3 answers

0
KawaLo On BEST ANSWER

Finally figured it out by using IntelliJ to inspect the structure, I can just set it the raw way :

c.Params = []gin.Param{
    {
        Key: "id",
        Value: "first document",
    },
}
0
Jonathan Chandler On

I was not able to get the accepted answer to work due to the c.Request.URL being nil in some of my tests.

Instead, you can set the query like this:

c.Request.URL, _ = url.Parse("?id=mock")
0
bdparrish On

Here was my solution to adding URL/query parameters

result := httptest.NewRecorder()
context, _ := gin.CreateTestContext(result)
context.Request, _ = http.NewRequest("GET", "?page=2", nil)