Interface RequestFixture
-
- All Known Subinterfaces:
GroovyRequestFixture
public interface RequestFixture
A contrived request environment, suitable for unit testingHandler
implementations.A request fixture emulates a request, and the effective state of the request handling in the handler pipeline.
A request fixture can be obtained by the
requestFixture()
method. However it is often more convenient to use the alternativehandle(Handler, Action)
method.- See Also:
handle(Handler)
-
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Modifier and Type Method Description RequestFixture
body(byte[] bytes, String contentType)
Sets the request body to be the given bytes, and adds aContent-Type
request header of the given value.RequestFixture
body(String text, String contentType)
Sets the request body to be the given string in utf8 bytes, and adds aContent-Type
request header of the given value.MultipartFileSpec
file()
A specification of a file to upload (see RFC2388).RequestFixture
file(String field, String filename, String data)
Uploads a file via a multipart form (see RFC2388).MultipartFormSpec
form()
A specification of a multipart form (see RFC2388).RequestFixture
form(Map<String,String> fields)
Sets the fields on a multipart form (see RFC2388).RegistrySpec
getRegistry()
A specification of the context registry.HandlingResult
handle(Handler handler)
Invokes the given handler with a newly createdContext
based on the state of this fixture.static HandlingResult
handle(Handler handler, Action<? super RequestFixture> action)
Unit test a singleHandler
.static HandlingResult
handle(Action<? super Chain> chainAction, Action<? super RequestFixture> requestFixtureAction)
Unit test aHandler
chain.HandlingResult
handleChain(Action<? super Chain> chainAction)
Similar tohandle(Handler)
, but for testing a handler chain.RequestFixture
header(CharSequence name, String value)
Set a request header value.RequestFixture
localAddress(com.google.common.net.HostAndPort local)
Set the local address to which this request is made.RequestFixture
method(String method)
Set the request method (case insensitive).RequestFixture
pathBinding(String boundTo, String pastBinding, Map<String,String> pathTokens)
Adds a path binding, with the given path tokens and parts.RequestFixture
pathBinding(String boundTo, String pastBinding, Map<String,String> pathTokens, String description)
Adds a path binding, with the given path tokens and parts.RequestFixture
pathBinding(Map<String,String> pathTokens)
Adds a path binding, with the given path tokens.RequestFixture
protocol(String protocol)
Set the HTTP protocol for the request.RequestFixture
registry(Action<? super RegistrySpec> action)
Configures the context registry.RequestFixture
remoteAddress(com.google.common.net.HostAndPort remote)
Set the remote address from which the request is made.static RequestFixture
requestFixture()
Create a request fixture, for unit testing ofhandlers
.RequestFixture
responseHeader(CharSequence name, String value)
Set a response header value.RequestFixture
serverConfig(Action<? super ServerConfigBuilder> action)
Configures the server config to have no base dir and given configuration.RequestFixture
timeout(int timeoutSeconds)
Sets the maximum time to allow the handler under test to produce a result.RequestFixture
uri(String uri)
The URI of the request.
-
-
-
Method Detail
-
handle
static HandlingResult handle(Handler handler, Action<? super RequestFixture> action) throws Exception
Unit test a singleHandler
.import ratpack.core.handling.Context; import ratpack.core.handling.Handler; import ratpack.test.handling.RequestFixture; import ratpack.test.handling.HandlingResult; import static org.junit.jupiter.api.Assertions.assertEquals; public class Example { public static class MyHandler implements Handler { public void handle(Context ctx) throws Exception { String outputHeaderValue = ctx.getRequest().getHeaders().get("input-value") + ":bar"; ctx.getResponse().getHeaders().set("output-value", outputHeaderValue); ctx.render("received: " + ctx.getRequest().getPath()); } } public static void main(String[] args) throws Exception { HandlingResult result = RequestFixture.handle(new MyHandler(), fixture -> fixture.header("input-value", "foo").uri("some/path") ); assertEquals("received: some/path", result.rendered(String.class)); assertEquals("foo:bar", result.getHeaders().get("output-value")); } }
- Parameters:
handler
- The handler to invokeaction
- The configuration of the context for the handler- Returns:
- A result object indicating what happened
- Throws:
HandlerTimeoutException
- if the handler takes more thantimeout(int)
seconds to send a response or callnext()
on the contextException
- any thrown byaction
- See Also:
handle(Action, Action)
-
handle
static HandlingResult handle(Action<? super Chain> chainAction, Action<? super RequestFixture> requestFixtureAction) throws Exception
Unit test aHandler
chain.import ratpack.func.Action; import ratpack.core.handling.Chain; import ratpack.test.handling.RequestFixture; import ratpack.test.handling.HandlingResult; import static org.junit.jupiter.api.Assertions.assertEquals; public class Example { public static class MyHandlers implements Action<Chain> { public void execute(Chain chain) throws Exception { chain.all(ctx -> { String outputHeaderValue = ctx.getRequest().getHeaders().get("input-value") + ":bar"; ctx.getResponse().getHeaders().set("output-value", outputHeaderValue); ctx.next(); }); chain.all(ctx -> ctx.render("received: " + ctx.getRequest().getPath()) ); } } public static void main(String[] args) throws Exception { HandlingResult result = RequestFixture.handle(new MyHandlers(), fixture -> fixture.header("input-value", "foo").uri("some/path") ); assertEquals("received: some/path", result.rendered(String.class)); assertEquals("foo:bar", result.getHeaders().get("output-value")); } }
- Parameters:
chainAction
- the definition of a handler chain to testrequestFixtureAction
- the configuration of the request fixture- Returns:
- a result object indicating what happened
- Throws:
HandlerTimeoutException
- if the handler takes more thantimeout(int)
seconds to send a response or callnext()
on the contextException
- any thrown bychainAction
orrequestFixtureAction
- See Also:
handle(Handler, Action)
-
requestFixture
static RequestFixture requestFixture()
Create a request fixture, for unit testing ofhandlers
.- Returns:
- a request fixture
- See Also:
handle(Handler, Action)
,handle(Action, Action)
-
body
RequestFixture body(byte[] bytes, String contentType)
Sets the request body to be the given bytes, and adds aContent-Type
request header of the given value.By default the body is empty.
- Parameters:
bytes
- the request body in bytescontentType
- the content type of the request body- Returns:
- this
-
body
RequestFixture body(String text, String contentType)
Sets the request body to be the given string in utf8 bytes, and adds aContent-Type
request header of the given value.By default the body is empty.
- Parameters:
text
- the request body as a stringcontentType
- the content type of the request body- Returns:
- this
-
file
MultipartFileSpec file()
A specification of a file to upload (see RFC2388).Can be used to construct a multipart form with files
- Returns:
- a specification of a multipart file
-
file
RequestFixture file(String field, String filename, String data)
Uploads a file via a multipart form (see RFC2388).- Parameters:
field
- form field namefilename
- filename of uploaded filedata
- content of file- Returns:
- this
-
form
MultipartFormSpec form()
A specification of a multipart form (see RFC2388).Can be used to construct a multipart form with name value pairs and files
Note that more than one value and more than one file can be associated with a single field
- Returns:
- a specification of a multipart form
-
form
RequestFixture form(Map<String,String> fields)
Sets the fields on a multipart form (see RFC2388).- Parameters:
fields
- map of field name to field value- Returns:
- this
-
getRegistry
RegistrySpec getRegistry()
A specification of the context registry.Can be used to make objects (e.g. support services) available via context registry lookup.
By default, only a
ServerErrorHandler
andClientErrorHandler
are in the context registry.- Returns:
- a specification of the context registry
-
handle
HandlingResult handle(Handler handler) throws HandlerTimeoutException
Invokes the given handler with a newly createdContext
based on the state of this fixture.The return value can be used to examine the effective result of the handler.
A result may be one of the following:
- The sending of a response via one of the
Response.send()
methods - Rendering to the response via the
Context.render(Object)
- Raising of a client error via
Context.clientError(int)
- Raising of a server error via
Context.error(Throwable)
- Raising of a server error by the throwing of an exception
- Delegating to the next handler by invoking one of the
Context.next()
methods
inserted
by the handler under test will be invoked. If the last inserted handler delegates to the next handler, the handling will terminate with a result indicating that the effective result was delegating to the next handler.This method blocks until a result is achieved, even if the handler performs an asynchronous operation (such as performing
blocking IO
). As such, a time limit on the execution is imposed which by default is 5 seconds. The time limit can be changed via thetimeout(int)
method. If the time limit is reached, aHandlerTimeoutException
is thrown.- Parameters:
handler
- the handler to test- Returns:
- the effective result of the handling
- Throws:
HandlerTimeoutException
- if the handler does not produce a result in the time limit defined by this fixture
- The sending of a response via one of the
-
handleChain
HandlingResult handleChain(Action<? super Chain> chainAction) throws Exception
Similar tohandle(Handler)
, but for testing a handler chain.- Parameters:
chainAction
- the handler chain to test- Returns:
- the effective result of the handling
- Throws:
HandlerTimeoutException
- if the handler does not produce a result in the time limit defined by this fixtureException
- any thrown bychainAction
-
header
RequestFixture header(CharSequence name, String value)
Set a request header value.By default there are no request headers.
- Parameters:
name
- the header namevalue
- the header value- Returns:
- this
-
serverConfig
RequestFixture serverConfig(Action<? super ServerConfigBuilder> action) throws Exception
Configures the server config to have no base dir and given configuration.By default the server config is equivalent to
ServerConfig.builder()
.build()
.- Parameters:
action
- configuration of the server config- Returns:
- this
- Throws:
Exception
- any thrown byaction
-
method
RequestFixture method(String method)
Set the request method (case insensitive).The default method is
"GET"
.- Parameters:
method
- the request method- Returns:
- this
-
pathBinding
RequestFixture pathBinding(Map<String,String> pathTokens)
Adds a path binding, with the given path tokens.By default, there are no path tokens and no path binding.
- Parameters:
pathTokens
- the path tokens to make available to the handler(s) under test- Returns:
- this
-
pathBinding
RequestFixture pathBinding(String boundTo, String pastBinding, Map<String,String> pathTokens)
Adds a path binding, with the given path tokens and parts.By default, there are no path tokens and no path binding.
- Parameters:
boundTo
- the part of the request path that the binding bound topastBinding
- the part of the request path pastboundTo
pathTokens
- the path tokens and binding to make available to the handler(s) under test- Returns:
- this
-
pathBinding
RequestFixture pathBinding(String boundTo, String pastBinding, Map<String,String> pathTokens, String description)
Adds a path binding, with the given path tokens and parts.By default, there are no path tokens and no path binding.
- Parameters:
boundTo
- the part of the request path that the binding bound topastBinding
- the part of the request path pastboundTo
pathTokens
- the path tokens and binding to make available to the handler(s) under testdescription
- the description of the request path binding- Returns:
- this
-
registry
RequestFixture registry(Action<? super RegistrySpec> action) throws Exception
Configures the context registry.- Parameters:
action
- a registry specification action- Returns:
- this
- Throws:
Exception
- any thrown byaction
-
responseHeader
RequestFixture responseHeader(CharSequence name, String value)
Set a response header value.Can be used to simulate the setting of a response header by an upstream handler.
By default there are no request headers.
- Parameters:
name
- the header namevalue
- the header value- Returns:
- this
-
timeout
RequestFixture timeout(int timeoutSeconds)
Sets the maximum time to allow the handler under test to produce a result.As handlers may execute asynchronously, a maximum time limit must be used to guard against never ending handlers.
- Parameters:
timeoutSeconds
- the maximum number of seconds to allow the handler(s) under test to produce a result- Returns:
- this
-
uri
RequestFixture uri(String uri)
The URI of the request.No encoding is performed on the given value. It is expected to be a well formed URI path string (potentially including query and fragment strings)
- Parameters:
uri
- the URI of the request- Returns:
- this
-
remoteAddress
RequestFixture remoteAddress(com.google.common.net.HostAndPort remote)
Set the remote address from which the request is made.Effectively the return value of
Request.getRemoteAddress()
.- Parameters:
remote
- the remote host and port address- Returns:
- this
-
localAddress
RequestFixture localAddress(com.google.common.net.HostAndPort local)
Set the local address to which this request is made.Effectively the return value of
Request.getLocalAddress()
.- Parameters:
local
- the local host and port address- Returns:
- this
-
protocol
RequestFixture protocol(String protocol)
Set the HTTP protocol for the request.- Parameters:
protocol
- The string representation of the HTTP protocol.- Returns:
- this
-
-