Search code examples
unit-testinggotestcase

How do I test my handler which require tokens to call data services


This is the code written in the handler, which gets the token required to call the data service.

m2m, err := h.getM2MToken(ctx)

if err != nil {
    return lc.SetResponse(&events.APIGatewayV2HTTPResponse{
        StatusCode: http.StatusInternalServerError,
        Body:       "Internal Server Error (m2m)",
    })
}

//Get the bearer token
userToken, err := h.getBearer(req.Headers)
if err != nil {
    xray.AddError(ctx, err)
    return lc.SetResponse(&events.APIGatewayV2HTTPResponse{
        StatusCode: http.StatusInternalServerError,
        Body:       "Internal Server Error (bearer)",
    })
}

Solution

  • My suggestion is to first try abstracting the inputs that you sent to a method

    Like instead of this

    userToken, err := h.getBearer(req.Headers)
    

    You can pass specify interfaces like

    type userTokenInput struct {}
    uti := userTokenInput{} 
    userToken, err := h.getBearer(uti)
    

    The above helps you to have control over input which makes testing easier

    For network calls try using some mock HTTP client which can return expected data you can follow this for mock HTTP client https://www.thegreatcodeadventure.com/mocking-http-requests-in-golang/