Home > Software design >  How do I test my handler which require tokens to call data services
How do I test my handler which require tokens to call data services

Time:11-01

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)",
    })
}

CodePudding user response:

If the service does not work without a token, you will have to provide one.

If the calls you will be doing should not be seen on the real target system for whatever reason, you will need a different target system for testing.

  • Ask the provider if they have a test installation you can use.
  • Consider testing against a mock.

CodePudding user response:

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/

  • Related