Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set an url parameter in gin context for testing purpose

Tags:

testing

go

go-gin

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.

like image 560
KawaLo Avatar asked Dec 23 '22 16:12

KawaLo


1 Answers

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",
    },
}
like image 193
KawaLo Avatar answered Jan 25 '23 23:01

KawaLo