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

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

Introduction

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

Prototype

MockHttpServletResponse

Source Link

Usage

From source file:org.jasig.cas.support.oauth.web.OAuth20WrapperControllerTests.java

@Test
public void verifyNoPostForAuthCallbackCtrl() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);

    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("text/plain", mockResponse.getContentType());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

From source file:com.ge.predix.acs.commons.web.RestErrorHandlerTest.java

@Test
public void testRestApiException() {
    RestErrorHandler errorHandler = new RestErrorHandler();

    HttpServletRequest request = new MockHttpServletRequest();
    HttpServletResponse response = new MockHttpServletResponse();
    Exception e = new RestApiException(HttpStatus.NOT_ACCEPTABLE, "NOT_ACCEPTABLE",
            "Not acceptable Error Message");

    ModelAndView errorResponse = errorHandler.createApiErrorResponse(e, request, response);

    // Custom error status code 406
    Assert.assertEquals(response.getStatus(), HttpStatus.NOT_ACCEPTABLE.value());

    Assert.assertNotNull(errorResponse);
    Assert.assertNotNull(errorResponse.getModel().get("ErrorDetails"));

    // Response payload with customer error code and message
    assertRestApiErrorResponse(errorResponse, "NOT_ACCEPTABLE", "Not acceptable Error Message");

}

From source file:org.eclipse.virgo.snaps.core.SnapHostFilterTests.java

@Test
public void testRouteToChain() throws IOException, ServletException {
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setPathInfo("/hotels/booking");

    Snap snap = createMock(Snap.class);
    FilterChain chain = createMock(FilterChain.class);
    chain.doFilter(request, response);/*from  w  w w  . ja  va  2  s  .c om*/
    expectLastCall();

    MockServletContext servletContext = new MockServletContext();
    MockFilterConfig config = new MockFilterConfig(servletContext);

    replay(snap, chain);
    TestFilter filter = new TestFilter();
    filter.init(config);
    filter.doFilter(request, response, chain);
    filter.destroy();
    verify(snap, chain);
}

From source file:alpha.portal.webapp.controller.CardFormControllerTest.java

/**
 * Test on submit.//www .ja v a 2  s .com
 * 
 * @throws Exception
 *             the exception
 */
@Test
public void testOnSubmit() throws Exception {
    final MockHttpServletRequest request = this.newPost("/cardform");
    final String view = this.c.onSubmit(this.alphaCard, null, request, new MockHttpServletResponse());
    Assert.assertEquals("redirect:/caseform?caseId=" + CardFormControllerTest.CASE_ID, view);
}

From source file:com.comcast.video.dawg.show.video.VideoSnapTest.java

@Test
public void testAddImagesToZipFile() throws IOException {
    String imageIds[] = { "", "", "" };
    MockHttpSession session = new MockHttpSession();
    MockHttpServletResponse response = new MockHttpServletResponse();
    UniqueIndexedCache<BufferedImage> imgCache = ClientCache.getClientCache(session).getImgCache();
    imageIds[0] = imgCache.storeItem(PC_IMG);
    imageIds[1] = imgCache.storeItem(PC_IMG);
    imageIds[2] = null;//from  w w w .jav a2 s.  com
    String deviceIds[] = { "000000000001", "000000000002", "000000000003" };
    int expectedZipSizeInBytes = 28954;

    VideoSnap videoSnap = new VideoSnap();

    videoSnap.addImagesToZipFile(imageIds, deviceIds, response, session);
    Assert.assertEquals(response.getContentType(), "application/zip", "Content type is not in zip format");
    String header = response.getHeader("Content-Disposition");
    Assert.assertTrue(header.contains("attachment"), "Response header does not indicates attachment");
    Assert.assertTrue(header.contains(".zip"), "Attached file is not in zip format");
    Assert.assertEquals(response.getContentAsByteArray().length, expectedZipSizeInBytes,
            "Zip file size in http response is not matching with expected zip size.");

}

From source file:org.geomajas.gwt.server.mvc.GeomajasControllerTest.java

@Test
public void testMockWebContext() throws ServletException, IOException {
    // create mock context that loads from the classpath
    MockServletConfig config = new MockServletConfig();
    MockHttpServletRequest request = new MockHttpServletRequest(config.getServletContext());
    request.setContentType("text/x-gwt-rpc");
    request.setCharacterEncoding("UTF-8");
    request.setContent(("6|0|10|http://apps.geomajas.org/explorer/be.geosparc.Explorer/"
            + "|54044FB0C988344F1715C8B91330B0A2|org.geomajas.gwt.client.GeomajasService|"
            + "execute|org.geomajas.gwt.client.command.GwtCommand/4093389776|command.configuration.GetMap|"
            + "org.geomajas.command.dto.GetMapConfigurationRequest/104733661|explorer|mainMap|"
            + "ss.TqRPfHFh24NVxB|1|2|3|4|1|5|5|6|7|8|9|0|10|").getBytes("UTF-8"));
    request.addHeader("X-GWT-Permutation", "54044FB0C988344F1715C8B91330B0A2");
    request.addHeader("X-GWT-Module-Base", "http://test/module/");
    MockHttpServletResponse response = new MockHttpServletResponse();
    defaultController.setServletConfig(config);
    defaultController.doPost(request, response);
    // expect the message of the out-dated 1.3 policy of GWT
    Assert.assertTrue(response.getContentAsString()
            .contains("Type 'org.geomajas.gwt.client.command.GwtCommand' was not assignable"
                    + " to 'com.google.gwt.user.client.rpc.IsSerializable'"));
}

From source file:fragment.web.LogoControllerTest.java

@Test
public void testGetProductLogo() {

    logoController.getProductLogo("2", map, response);
    checkCorrectnessForNullPath();// ww w  .j  a  v  a2s. com

    response = new MockHttpServletResponse();
    logoController.getProductLogo("1", map, response);
    checkCorrectnessOfMethod(response);

}

From source file:org.auraframework.integration.test.http.resource.BootstrapTest.java

@SuppressWarnings("unchecked")
@Test//from w  ww .  ja v  a  2 s . c o  m
public void testWriteSetsOkResponseWithErrorPayloadWhenTokenValidationFails() throws Exception {
    // Arrange
    if (contextService.isEstablished()) {
        contextService.endContext();
    }
    DefDescriptor<ApplicationDef> appDesc = addSourceAutoCleanup(ApplicationDef.class,
            "<aura:application></aura:application>");
    AuraContext context = contextService.startContext(AuraContext.Mode.PROD, AuraContext.Format.MANIFEST,
            AuraContext.Authentication.AUTHENTICATED, appDesc);

    HttpServletRequest request = mock(HttpServletRequest.class);
    MockHttpServletResponse response = new MockHttpServletResponse();

    ConfigAdapter configAdapter = mock(ConfigAdapter.class);

    Bootstrap bootstrap = getBootstrap();
    bootstrap.setConfigAdapter(configAdapter);

    // Force token validation to fail
    when(configAdapter.validateBootstrap(anyString())).thenReturn(false);

    // Act
    bootstrap.write(request, response, context);

    // Assert
    // JWT token failure returns 2xx response code with error payload so browser executes it
    assertEquals(HttpStatus.SC_OK, response.getStatus());

    /*
     * Expected appBootstrap object
     * window.Aura.appBootstrap = {
     *     "error":{
     *          "message":"Invalid jwt parameter"
     *     }
     * };
     */
    String content = response.getContentAsString();
    Pattern pattern = Pattern.compile("appBootstrap = (\\{.*\\});", Pattern.DOTALL);
    Matcher matcher = pattern.matcher(content);
    assertTrue("Failed to find appBootstrap in response: " + content, matcher.find());

    Map<String, Object> appBootstrap = (Map<String, Object>) new JsonReader().read(matcher.group(1));
    Map<String, Object> error = (Map<String, Object>) appBootstrap.get("error");

    String actualMessage = error.get("message").toString();
    // refer to the message in Bootstrap.write()
    String expectedMessage = "Invalid jwt parameter";
    assertThat("Failed to find expected message: " + content, actualMessage, containsString(expectedMessage));
}

From source file:org.openmrs.web.controller.encounter.EncounterTypeFormControllerTest.java

@Test
public void shouldSaveEncounterTypeWhenEncounterTypesAreNotLocked() throws Exception {
    EncounterService es = Context.getEncounterService();

    EncounterTypeFormController controller = (EncounterTypeFormController) applicationContext
            .getBean("encounterTypeForm");
    controller.setApplicationContext(applicationContext);
    controller.setSuccessView("index.htm");
    controller.setFormView("EncounterType.form");

    MockHttpServletRequest request = new MockHttpServletRequest("GET",
            "/admin/encounters/encounterType.form?encounterTypeId=1");
    request.setSession(new MockHttpSession(null));
    HttpServletResponse response = new MockHttpServletResponse();
    controller.handleRequest(request, response);

    request.setMethod("POST");

    request.addParameter("action", "Save EncounterType");

    ModelAndView mav = controller.handleRequest(request, response);

    Assert.assertSame(controller.getFormView(), mav.getViewName());
    Assert.assertNotEquals("The save attempt should have passed!", "index.htm", mav.getViewName());
    Assert.assertNotNull(es.getEncounterType(1));
}