Passionate Engineer
Passionate Engineer

Reputation: 10422

Go - How to test with http.NewRequest

I've got below code for testing http request:

func TestAuthenticate(t *testing.T) {
    api := &ApiResource{}
    ws := new(restful.WebService)
    ws.Consumes(restful.MIME_JSON, restful.MIME_XML)
    ws.Produces(restful.MIME_JSON, restful.MIME_JSON)
    ws.Route(ws.POST("/login").To(api.Authenticate))
    restful.Add(ws)

    bodyReader := strings.NewReader("<request><Username>42</Username><Password>adasddsa</Password><Channel>M</Channel></request>")

    httpRequest, _ := http.NewRequest("POST", "/login", bodyReader)
//  httpRequest.Header.Set("Content-Type", restful.MIME_JSON)
    httpRequest.Header.Set("Content-Type", restful.MIME_XML)
    httpWriter := httptest.NewRecorder()

    restful.DefaultContainer.ServeHTTP(httpWriter, httpRequest)
}

I tried to use json as a string with same NewReader and also tried to use struct with json.Marshal.

Neither of them works.

Is there a method where I can code bodyReader for a valid third parameter for http.NewRequest?

Similar request as input for NewReader in JSON is:

bodyReader := strings.NewReader("{'Username': '12124', 'Password': 'testinasg', 'Channel': 'M'}")

Struct fields are is: Username, Password, Channel

Upvotes: 8

Views: 9002

Answers (1)

Thundercat
Thundercat

Reputation: 121199

The JSON is invalid. JSON uses " for quoting strings, not '.

Use this line of code to create the request body:

bodyReader := strings.NewReader(`{"Username": "12124", "Password": "testinasg", "Channel": "M"}`)

I used a raw string literal to avoid quoting the " in the JSON text.

Upvotes: 9

Related Questions