Skip to content

Instantly share code, notes, and snippets.

@danbev
Last active December 13, 2015 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danbev/4983976 to your computer and use it in GitHub Desktop.
Save danbev/4983976 to your computer and use it in GitHub Desktop.
Route testing

Simplifying Route testing

For AEROGEAR-778 we have been looking into making it easier to test routes. We have been using Mockito which works nicely, but there was a bit of duplicated code spread across different tests and also the test were not that easy to read.
Below are examples of one of the tests before and after, hopefully the after will be easier to read, but if not, then please let us know.

Before

@Test
    public void testRestRouteWithPathParam() throws Exception {
        final RoutingModule routingModule = new AbstractRoutingModule() {
            @Override
            public void configuration() {
                route()
                        .from("/car/{id}").roles("admin")
                        .on(GET)
                        .produces(mockJsp(), mockJson())
                        .to(SampleController.class).find(param("id"));
            }
        };
        final Routes routes = routingModule.build();
        when(request.getMethod()).thenReturn(RequestMethod.GET.toString());
        when(request.getServletContext()).thenReturn(servletContext);
        when(servletContext.getContextPath()).thenReturn("/abc");
        when(request.getRequestURI()).thenReturn("/abc/car/3");
        when(request.getHeader("Accept")).thenReturn("application/json");
        when(jsonResponder.accepts("application/json")).thenReturn(true);
        when(jsonResponder.mediaType()).thenReturn(mockJson());
        final Route route = routes.routeFor(GET, "/car/{id}", acceptHeaders(JSON.getMediaType()));
        router.process(new RouteContext(route, request, response, routes));
        verify(jsonResponder).respond(anyObject(), any(RouteContext.class));
    }

After

@Test
    public void testRestRouteWithPathParam() throws Exception {
        final RouteTester routeTester = RouteTester.from(new AbstractRoutingModule() {
            @Override
            public void configuration() {
                route()
                        .from("/car/{id}").roles("admin")
                        .on(GET)
                        .produces(JSP, JSON)
                        .to(SampleController.class).find(param("id"));
            }
        });
        routeTester.acceptHeader(JSON).processGetRequest("/car/3");
        verify(routeTester.<SampleController>getController()).find("3");
        verify(routeTester.jsonResponder()).respond(any(), any(RouteContext.class));
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment