Home > Back-end >  mocking http poster in test how to take a resp any type to *http.response to set status code
mocking http poster in test how to take a resp any type to *http.response to set status code

Time:10-23

as above,

httpPoster := fakeHTTPPoster{
        fnPost: func(ctx context.Context, postURL string, req any, resp any) error {
            
            resp.(*http.Response).StatusCode = 200
            return nil
        },
    }

Trying to turn that response into *http.response so I can set a status code to allow a test to pass, any clue on how to resolve this?

The struct and method that is a mock relating to the above is,

type fakeHTTPPoster struct {
    fnPost func(ctx context.Context, postURL string, req any, resp any) error
}

func (f fakeHTTPPoster) Post(ctx context.Context, postURL string, req any, resp any) error {
    return f.fnPost(ctx, postURL, req, resp)
}


//The o.g. interface
type HTTPPoster interface {
    Post(ctx context.Context, postURL string, req, resp any) error
}

The output being, i want resp.StatusCode=200, so it won't fail a test of restp.StatusCode !=200{error}

CodePudding user response:

If you want to do a real HTTP request in fnpost, here is the sample codes

    httpPoster := fakeHTTPPoster{
        fnPost: func(ctx context.Context, postURL string, req any, resp any) error {
            client := http.Client{Timeout: time.Duration(10) * time.Second}

            postReq, ok := req.(*http.Request)
            if !ok {
                return fmt.Errorf("invalid http request")
            }
            postReq.URL.RawPath = postURL
            resp, err := client.Do(postReq)
            if err != nil {
                // ignore the err ?
            }

            resp.(*http.Response).StatusCode = 200
            return nil
        },
    }
  •  Tags:  
  • go
  • Related