Interface RequestFixture

  • All Known Subinterfaces:
    GroovyRequestFixture

    public interface RequestFixture
    A contrived request environment, suitable for unit testing Handler 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 alternative handle(Handler, Action) method.

    See Also:
    handle(Handler)
    • Method Detail

      • handle

        static HandlingResult handle​(Handler handler,
                                     Action<? super RequestFixture> action)
                              throws Exception
        Unit test a single Handler.
        
         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 invoke
        action - The configuration of the context for the handler
        Returns:
        A result object indicating what happened
        Throws:
        HandlerTimeoutException - if the handler takes more than timeout(int) seconds to send a response or call next() on the context
        Exception - any thrown by action
        See Also:
        handle(Action, Action)
      • handle

        static HandlingResult handle​(Action<? super Chain> chainAction,
                                     Action<? super RequestFixture> requestFixtureAction)
                              throws Exception
        Unit test a Handler 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 test
        requestFixtureAction - the configuration of the request fixture
        Returns:
        a result object indicating what happened
        Throws:
        HandlerTimeoutException - if the handler takes more than timeout(int) seconds to send a response or call next() on the context
        Exception - any thrown by chainAction or requestFixtureAction
        See Also:
        handle(Handler, Action)
      • body

        RequestFixture body​(byte[] bytes,
                            String contentType)
        Sets the request body to be the given bytes, and adds a Content-Type request header of the given value.

        By default the body is empty.

        Parameters:
        bytes - the request body in bytes
        contentType - 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 a Content-Type request header of the given value.

        By default the body is empty.

        Parameters:
        text - the request body as a string
        contentType - 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 name
        filename - filename of uploaded file
        data - 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 and ClientErrorHandler 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 created Context 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:

        Note that any handlers 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 the timeout(int) method. If the time limit is reached, a HandlerTimeoutException 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
      • handleChain

        HandlingResult handleChain​(Action<? super Chain> chainAction)
                            throws Exception
        Similar to handle(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 fixture
        Exception - any thrown by chainAction
      • header

        RequestFixture header​(CharSequence name,
                              String value)
        Set a request header value.

        By default there are no request headers.

        Parameters:
        name - the header name
        value - the header value
        Returns:
        this
      • 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 to
        pastBinding - the part of the request path past boundTo
        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 to
        pastBinding - the part of the request path past boundTo
        pathTokens - the path tokens and binding to make available to the handler(s) under test
        description - the description of the request path binding
        Returns:
        this
      • 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 name
        value - 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