1

I have some code that makes get requests to a dynamic website, which I want to test. Obviously the tests need to be run by anyone at any time, so rather than actually use the REST API, is it possible to put a json string into an *http.Response for testing purposes.

example code:

func get (c *http.Response, err error) (string, error) {
    //code
}

test file:

func TestGet(t *testing.T) {
    //code to have put json string for test *http.Response
    get(???, nil)

}
1
  • Do you want somehow unmarshal a json string into an http.Response object? You can read a saved response via http.ReadResponse Commented Sep 23, 2016 at 20:00

1 Answer 1

2

You want to use a bytes.Buffer to turn the data you have into an io.Reader, and NopCloser (from io/ioutil) to make it an io.ReadCloser

r := &http.Response{
    Status: "200 OK",
    StatusCode: 200,
    // etc., lots more fields needed here.
    Body: ioutil.NopCloser(bytes.NewBufferString(json))
}

If you have your json in a []byte, then use NewBuffer instead of NewBufferString.

Sign up to request clarification or add additional context in comments.

2 Comments

Is the json in this case a string, and if so, how do I hard code json as a string (since it will have multiple quotes in the json
@user6586806 your question implied you already had a JSON string. Anyway, you can use the raw string (`like this`) quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.