2

I'm writing some test to check some responses on one of my APIs but the resty mock client is not being sent to the original function. I created a mock client for resty using the readme example but the info on mocking resty is very incomplete.

The response of my function always return blank, so I'm not sure of what I'm doing wrong. Any tips helps me a lot.

func TestService_getAccessToken(t *testing.T) {
tests := []struct {
    name           string
    response       string
    responseStatus int
    want           *model.Token
}{
    {
        "success",
        `{
            "access_token": "aQWsadw21sdax",
            "token_type": "Bearer",
            "expires_in": 300
        }`,
        http.StatusOK,
        &model.Token{
            AccessToken: "aQWsadw21sdax",
        },
    },
}
for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        cfg, err := config.Load("./../../config/testdata/config.yml")
        client := resty.New()
        httpmock.ActivateNonDefault(client.GetClient())
        responder := httpmock.NewStringResponder(200, tt.response)
        s := &Service{
            Client: client,
            cfg:    cfg,
        }
        httpmock.RegisterResponder("POST", s.cfg.Services.Lego.AuthHost, responder)
        if err != nil {
            t.Errorf("Service.getAccessToken() = %v", err)
        }
        if got := s.getAccessToken(); !reflect.DeepEqual(got, tt.want) {
            t.Errorf("Service.getAccessToken() = %v, want %v", got, tt.want)
        }
    })
}

}

Here is my function info

type Service struct {
    Client *resty.Client
    cfg    *config.Configuration
}

func New(cfg *config.Configuration) *Service {
    c := resty.New().
        SetTimeout(cfg.Services.Lego.Timeout)

    return &Service{Client: c, cfg: cfg}
}

func (s *Service) getAccessToken() *model.Token {
    resp, _ := s.Client.SetHostURL(s.cfg.Services.Lego.AuthHost).R().
        SetBasicAuth(s.cfg.Services.Lego.Username, s.cfg.Services.Lego.Password).
        SetFormData(map[string]string{
            "grant_type": "client_credentials",
        }).
        SetResult(model.Token{}).
        Post("/v2/access_token")

    return resp.Result().(*model.Token)
}
parebi
  • 29
  • 2
  • 1
    You must set the full path or a regex to match when registering the responder, try adding the full path, for example `http://test-auth.com/v2/access_token`. Additionally, try logging the error that the resty call might return in your function code – Pablo Flores Mar 11 '21 at 03:55

0 Answers0