Requests

test.NewRequest describes an HTTP application that will be processed by the application during a test.

The request uses the same server pipeline as a real request. ctx.Request inside the proven handler.


Properties

PropertyDescription
MethodHTTP method of the request.
URLRoute and query requested.
URLParamsParameters added to the query.
HeadersHeaders sent to the server.
CookiesInitial cookies of the request.
BodyBody sent to the handler.

Method

Method defines the HTTP method. The package offers the constants GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS.

gox
request := test.NewRequest{Method: test.GET, URL: "/users"}

If omitted, GOX uses GET.


URL

URL defines the route that will receive the application and may include an existing query.

gox
request := test.NewRequest{
	Method: test.GET,
	URL: "/users?active=true",
}

If omitted, GOX uses /.


URLParams

URLParams adds parameters to the URL.

gox
request := test.NewRequest{
	Method: test.GET,
	URL: "/users",
	URLParams: test.RequestURLParams{
		"name": "George",
		"page": "2",
	},
}

Headers

Headers add headers to the request.

gox
request := test.NewRequest{
	Method: test.GET,
	URL: "/profile",
	Headers: test.RequestHeaders{
		"Authorization": "Bearer token",
		"Accept": "application/json",
	},
}

Cookies

Cookies add cookies before processing the request.

gox
request := test.NewRequest{
	Method: test.GET,
	URL: "/profile",
	Cookies: test.RequestCookies{
		"language": "es",
	},
}

The cookies returned by the server are also automatically kept between the steps of a pipeline.


Body

Body accepts a value produced by test.RequestBody.

MethodContent
Empty()Body empty.
Raw(content)Text with text/plain; charset=utf-8.
RawWithType(content, contentType)Text with an explicit Content-Type.
Query(values)Format application/x-www-form-urlencoded.
FormData(values)Form fields encoded.
JSON(value)Serialized value as JSON.
gox
request := test.NewRequest{
	Method: test.POST,
	URL: "/users",
	Body: test.RequestBody.JSON(test.Map{
		"name": "George",
		"active": true,
	}),
}

The JSON bodies accept the GOX-compatible values.


Integration with Go

NewRequest is a structure and its auxiliary collections are typed maps. This allows to build requests by means of literals, variables and auxiliary functions in the same way as any other Go value.

Before running the handler, GOX turns the structure into an HTTP request into memory. The Content-Type is obtained from the body when it was not explicitly established in Headers.


Best practices

  • Use the method constants provided by test.
  • It includes only the headers relevant to the proven behavior.
  • Use RequestBody.JSON() for structured data.
  • Separate the parameters of the query from the content sent in the body.
  • Test the persistence of cookies by means of a pipeline when it is part of the flow.

See also

Next step

Continue with Expectations to validate the response produced by an request.

Expectations