Example usage for org.springframework.mock.web MockHttpServletResponse getStatus

List of usage examples for org.springframework.mock.web MockHttpServletResponse getStatus

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletResponse getStatus.

Prototype

@Override
    public int getStatus() 

Source Link

Usage

From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java

/**
 * Test get request for retrieving an item.
 * @throws Exception/*from  w w  w.  j a v  a  2 s .  c  om*/
 */
public void testGetOperation() throws Exception {
    final Integer userId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");
    final List<Integer> parentItemIds = new ArrayList<Integer>();
    parentItemIds.add(userId);
    final List<Integer> itemIds = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 10, "blog",
            parentItemIds);

    // Execute successful login request.
    final Subject subject = getSubjectFromASuccessfulRequest();

    // Create a new servlet request.
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/service/get/" + itemIds.get(0) + ".xml");
    request.setMethod(METHOD_GET);
    // set parameters
    request.addParameter(WebConstants.PARAM_LOAD_RELATED_ITEMS, "true");
    request.addParameter(WebConstants.PARAM_RELATION_TYPES, "blog, user");
    request.addParameter(WebConstants.PARAM_MAX, "1");

    // set session id
    final MockHttpSession session = new MockHttpSession();
    session.setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
    request.setSession(session);
    final MockHttpServletResponse response = new MockHttpServletResponse();

    // Execute controller
    final ModelAndView modelAndView = mRestfulController.handleRequest(request, response);

    // Verify response
    assertNull("Model and view is ignored.", modelAndView);
    LOG.debug("Response - " + response.getContentAsString());
    final boolean stateTrue = response.getContentAsString().indexOf("false") == -1;
    assertTrue("This action should not return false", stateTrue);
    assertEquals("Response status is not 200.", RESTfulControllerImpl.STATUS_OK_200, response.getStatus());
}

From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java

@Test
public void testCopyMapWithLayers() throws Exception {
    Catalog catalog = getCatalog();/*from   w ww  . j  ava2 s .  co  m*/
    CatalogBuilder catalogBuilder = new CatalogBuilder(catalog);

    LayerInfo points = catalog.getLayerByName("cgf:Points");
    LayerInfo lines = catalog.getLayerByName("cgf:Lines");

    LayerGroupInfo map = catalog.getFactory().createLayerGroup();
    map.setWorkspace(catalog.getWorkspaceByName("cgf"));
    map.setName("map1");
    map.getLayers().add(lines);
    map.getLayers().add(points);
    map.getStyles().add(null);
    map.getStyles().add(null);
    catalogBuilder.calculateLayerGroupBounds(map);
    catalog.add(map);

    assertNotNull(catalog.getLayerGroupByName("cgf:map1"));
    assertNotNull(catalog.getLayerByName("cgf:Points"));
    assertNotNull(catalog.getLayerByName("cgf:Lines"));
    assertNull(catalog.getLayerGroupByName("cgf:map2"));
    assertNull(catalog.getLayerByName("cgf:renamedLayer"));
    assertNull(catalog.getLayerByName("cgf:Lines-map"));

    JSONObj obj = new JSONObj();
    obj.put("name", "map2");
    obj.put("copylayers", true);
    obj.putArray("layers").addObject().put("name", "renamedLayer").putObject("layer").put("name", "Points")
            .put("workspace", "cgf");

    MockHttpServletResponse resp = putAsServletResponse("/app/api/maps/cgf/map1/copy", obj.toString(),
            MediaType.APPLICATION_JSON_VALUE);
    assertEquals(200, resp.getStatus());

    assertNotNull(catalog.getLayerGroupByName("cgf:map2"));
    assertNotNull(catalog.getLayerByName("cgf:renamedLayer"));
    assertNotNull(catalog.getLayerByName("cgf:Lines-map"));
}

From source file:nz.net.catalyst.mobile.dds.CapabilitySerivceControllerTest.java

@Test
public void testRequiredParams() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/services/v1/get_capabilities");
    MockHttpServletResponse response = new MockHttpServletResponse();

    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("user-agent",
            "Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE71-1/100.07.57; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413");
    String headersStr = mapper.writeValueAsString(headers);

    request.addParameter("headers", headersStr);

    try {// w  ww .  j a v a 2  s.  c  om
        handlerAdapter.handle(request, response, csController);
        fail("exception expected");
    } catch (MissingServletRequestParameterException e) {
        assertEquals("Required String[] parameter 'capability' is not present", e.getMessage());
    }

    request = new MockHttpServletRequest("GET", "/services/v1/get_capabilities");
    request.addParameter("capability", "device_id");

    try {
        handlerAdapter.handle(request, response, csController);
        fail("exception expected");
    } catch (MissingServletRequestParameterException e) {
        assertEquals("Required String parameter 'headers' is not present", e.getMessage());
        csController.handleMissingParameters(e, response);

        assertEquals(400, response.getStatus());
    }

}

From source file:com.doitnext.http.router.DefaultInvokerTest.java

@Test
public void testStoresCall() throws Exception {
    Route route = routesByName.get("getFavoritesForUser");
    Path path = route.getPathTemplate().match("/sports-api/teams/favorites/user1/a/b/c?query=String");
    Assert.assertNotNull(path);/*from ww  w  .j av a  2  s .c om*/
    PathMatch pm = new PathMatch(route, path);
    HttpMethod method = route.getHttpMethod();
    MockHttpServletRequest req = (MockHttpServletRequest) createHappyMockRequest(method, pm);
    req.setContentType("application/json; model=hashmap");
    MockHttpServletResponse resp = new MockHttpServletResponse();
    //executePathMatchTest(createPathMatchTestCaseId(pm),pm, req, resp);
    String testCaseId = createPathMatchTestCaseId(pm);
    HttpMethod httpmethod = pm.getRoute().getHttpMethod();
    InvokeResult invokeresult = invoker.invokeMethod(httpmethod, pm, req, resp);
    Assert.assertTrue(invokeresult.handled);
    if (invokeresult.success) {
        Assert.assertFalse(testCaseId, StringUtils.isEmpty(testCollectionImpl.getLastHttpMethodCalled()));
        HttpMethod methodCalled = HttpMethod.valueOf(testCollectionImpl.getLastHttpMethodCalled());
        Assert.assertEquals(testCaseId, pm.getRoute().getHttpMethod(), methodCalled);
        Assert.assertEquals(testCaseId, pm.getRoute().getImplMethod().getName(),
                testCollectionImpl.getLastMethodCalled());
    } else {
        verify(errorHandlerJson).handleResponse(eq(pm), eq(req), eq(resp), any(Throwable.class));
    }

    String content = resp.getContentAsString();
    Assert.assertEquals(200, resp.getStatus());
    Assert.assertEquals("{\"storePath\":\"a/b/c\",\"userId\":\"user1\"}", content);
}

From source file:nl.eveoh.sakai.mytimetable.tool.ToolControllerTest.java

@Test
public void testModel() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("GET");

    // Display two test events
    List<Event> testEvents = new ArrayList<Event>();
    testEvents.add(new Event());
    testEvents.add(new Event());

    Mockito.when(myTimetableService.getUpcomingEvents(Mockito.anyString())).thenReturn(testEvents);
    Mockito.when(configuration.getApplicationUri()).thenReturn("https://timetable.institution.ac.uk/");
    Mockito.when(configuration.getApplicationTarget()).thenReturn("_blank");

    ModelAndView modelAndView = toolController.handleRequest(request, response);

    Assert.assertTrue("Should contain events attribute.",
            modelAndView.getModelMap().containsAttribute("events"));
    Assert.assertTrue(modelAndView.getModelMap().containsAttribute("applicationUri"));
    Assert.assertTrue(modelAndView.getModelMap().containsAttribute("applicationTarget"));

    Assert.assertEquals("Should display 5 events.", 2,
            ((List<Event>) modelAndView.getModelMap().get("events")).size());
    Assert.assertEquals("https://timetable.institution.ac.uk/",
            modelAndView.getModelMap().get("applicationUri"));
    Assert.assertEquals("_blank", modelAndView.getModelMap().get("applicationTarget"));

    Assert.assertEquals(200, response.getStatus());
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testLastModified() throws Exception {
    String stage = systemInfo.getStagingProfile();
    systemInfo.setStagingProfile(SystemInfo.STAGE_PRODUCTION);
    try {//  w  ww  . j av  a 2s. c  o  m
        metadataRepository.update(id, new Updater<Metadata>() {
            @Override
            public void apply(@Nonnull Metadata entity) {
                entity.getDataInfo().setChangeDate(new ISODate("2012-01-18T15:04:43"));
            }
        });
        dataManager.indexMetadata(Lists.newArrayList("" + this.id));

        final String formatterName = "full_view";

        MockHttpServletRequest request = new MockHttpServletRequest();
        request.getSession();
        request.addParameter("h2IdentInfo", "true");

        MockHttpServletResponse response = new MockHttpServletResponse();
        formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
                new ServletWebRequest(request, response));
        final String lastModified = response.getHeader("Last-Modified");
        assertEquals("no-cache", response.getHeader("Cache-Control"));
        final String viewString = response.getContentAsString();
        assertNotNull(viewString);

        request = new MockHttpServletRequest();
        request.getSession();
        request.setMethod("GET");
        response = new MockHttpServletResponse();

        request.addHeader("If-Modified-Since", lastModified);
        formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
                new ServletWebRequest(request, response));
        assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getStatus());
        final ISODate newChangeDate = new ISODate();
        metadataRepository.update(id, new Updater<Metadata>() {
            @Override
            public void apply(@Nonnull Metadata entity) {
                entity.getDataInfo().setChangeDate(newChangeDate);
            }
        });

        dataManager.indexMetadata(Lists.newArrayList("" + this.id));

        request = new MockHttpServletRequest();
        request.getSession();
        request.setMethod("GET");
        response = new MockHttpServletResponse();

        request.addHeader("If-Modified-Since", lastModified);
        formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
                new ServletWebRequest(request, response));
        assertEquals(HttpStatus.SC_OK, response.getStatus());
    } finally {
        systemInfo.setStagingProfile(stage);
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimUserEndpointsTests.java

@Test
public void testHandleExceptionWithBadFieldName() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    endpoints.setMessageConverters(new HttpMessageConverter<?>[] { new ExceptionReportHttpMessageConverter() });
    View view = endpoints.handleException(new HttpMessageConversionException("foo"), request);
    ConvertingExceptionView converted = (ConvertingExceptionView) view;
    converted.render(Collections.<String, Object>emptyMap(), request, response);
    String body = response.getContentAsString();
    assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus());
    // System.err.println(body);
    assertTrue("Wrong body: " + body, body.contains("message\":\"foo"));
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimUserEndpointsTests.java

@Test
public void testHandleExceptionWithConstraintViolation() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    endpoints.setMessageConverters(new HttpMessageConverter<?>[] { new ExceptionReportHttpMessageConverter() });
    View view = endpoints.handleException(new DataIntegrityViolationException("foo"), request);
    ConvertingExceptionView converted = (ConvertingExceptionView) view;
    converted.render(Collections.<String, Object>emptyMap(), request, response);
    String body = response.getContentAsString();
    assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus());
    // System.err.println(body);
    assertTrue("Wrong body: " + body, body.contains("message\":\"foo"));
}