Class MockApi

  • All Implemented Interfaces:
    AutoCloseable, ApplicationUnderTest, CloseableApplicationUnderTest, EmbeddedApp

    public class MockApi
    extends Object
    implements EmbeddedApp
    A test harness for simulating behavior of remote APIs by starting an EmbeddedApp that will handle requests based on the content of the received request.

    MockApi provides functionality similar to WireMock and BetaMax.

    
     import ratpack.core.http.HttpMethod;
     import ratpack.core.http.client.HttpClient;
     import ratpack.test.embed.EmbeddedApp;
     import ratpack.test.handling.HandlerFactory;
     import ratpack.test.mock.MockApi;
    
     import static org.junit.jupiter.api.Assertions.assertEquals;
    
     public class Example {
       public static void main(String... args) throws Exception {
    
         HandlerFactory factory = request -> {
           if (request.getMethod() ==  HttpMethod.GET)  {
             return ctx -> ctx.render("get on remote API");
           }
           return ctx -> ctx.getResponse().status(400).send();
         };
    
         MockApi remoteApi = MockApi.of(factory);
    
         EmbeddedApp.fromHandlers(chain -> {
           chain.get("get", ctx ->
             ctx.get(HttpClient.class)
               .get(remoteApi.getAddress())
               .then(resp ->
                 resp.forwardTo(ctx.getResponse())
               )
           );
           chain.get("post", ctx ->
             ctx.get(HttpClient.class)
               .post(remoteApi.getAddress(), spec -> {})
               .then(resp ->
                 resp.forwardTo(ctx.getResponse())
               )
           );
         }).test(httpClient -> {
           assertEquals("get on remote API", httpClient.get("get").getBody().getText());
           assertEquals(400, httpClient.get("post").getStatusCode());
         });
       }
     }
     

    MockApi is particularly powerful when combined with Spock's Mock API by providing a Mock HandlerFactory to this class. Interactions to a remote API can then be validated inline to the specification by verifying the invocations of the mock HandlerFactory.

    
     import ratpack.groovy.test.embed.GroovyEmbeddedApp
     import ratpack.core.http.HttpMethod
     import ratpack.core.http.client.HttpClient
     import spock.lang.Specification
    
     import static ratpack.groovy.Groovy.groovyHandler
    
     class ApiSpec extends Specification {
    
       def "test api"() {
         given:
         MockApi remoteApi = MockApi.of(Mock(HandlerFactory))
    
         def app = GroovyEmbeddedApp.ratpack {
           handlers {
             get { ctx ->
               ctx.get(HttpClient).get(remoteApi.address).then { resp ->
                 resp.forwardTo(ctx.response)
               }
             }
           }
         }
    
         when:
         def resp = app.httpClient.get()
    
         then:
         1 * remoteApi.handlerFactory.receive {
           it.method == HttpMethod.GET
           it.path == ""
         } >> groovyHandler {
           render("remote ok")
         }
         resp.body.text == "remote ok"
       }
     }
     
    Since:
    1.7.0
    • Method Detail

      • getServer

        public RatpackServer getServer()
        Description copied from interface: EmbeddedApp
        The server for the application.

        Calling this method does not implicitly start the server.

        Specified by:
        getServer in interface EmbeddedApp
        Returns:
        The server for the application
      • getHandlerFactory

        public HandlerFactory getHandlerFactory()
        Retrieve the factory that generates handlers for requests.
        Returns:
        the HandlerFactory for this mock.
      • of

        public static MockApi of​(HandlerFactory factory)
        Creates an embedded Ratpack server which delegates handling to the provided factory.
        Parameters:
        factory - a factory that generates a Handler based on the incoming Request
        Returns:
        an embedded Ratpack app which delegates all requests to the provided factory.
        See Also:
        EmbeddedApp