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

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

Introduction

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

Prototype

public String getContentAsString() throws UnsupportedEncodingException 

Source Link

Document

Get the content of the response body as a String , using the charset specified for the response by the application, either through HttpServletResponse methods or through a charset parameter on the Content-Type .

Usage

From source file:com.liferay.frontend.js.loader.modules.extender.internal.JSLoaderModulesServletTest.java

@Test
public void testUnversionedModuleOutput() throws Exception {
    JSLoaderModulesServlet jsLoaderModulesServlet = buildJSLoaderModulesServlet(
            Collections.<String, Object>singletonMap("apply-versioning", Boolean.FALSE));

    JSLoaderModulesTracker jsLoaderModulesTracker = jsLoaderModulesServlet.getJSLoaderModulesTracker();

    ServiceReference<ServletContext> serviceReference = buildServiceReference("test", new Version("1.0.0"),
            true, 0, getResource("dependencies/config1.js"));

    jsLoaderModulesServlet.setJSLoaderModulesTracker(jsLoaderModulesTracker);

    jsLoaderModulesTracker.addingService(serviceReference);

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    jsLoaderModulesServlet.service(mockHttpServletRequest, mockHttpServletResponse);

    String content = mockHttpServletResponse.getContentAsString();

    content = content.replace('"', '\'');

    assertContains("'test': '/test-1.0.0'", content);
    assertContains("'test@1.0.0': '/test-1.0.0'", content);
    assertContains("'test/some.es':{'dependencies':['exports','test/other.es']}", content);
    assertNotContains("'test/some.es':{'dependencies':['exports','test@1.0.0/other.es']}", content);
    assertContains("'test/other.es':{'dependencies':['exports']}", content);
    assertNotContains("'test@1.0.0/some.es':{'dependencies':['exports'," + "'test@1.0.0/other.es']}", content);
    assertNotContains("'test@1.0.0/other.es':{'dependencies':['exports']}", content);
}

From source file:com.liferay.frontend.js.loader.modules.extender.internal.JSLoaderModulesServletTest.java

@Test
public void testMultipleVersionsModuleOutput() throws Exception {
    JSLoaderModulesServlet jsLoaderModulesServlet = buildJSLoaderModulesServlet(
            Collections.<String, Object>singletonMap("applyVersioning", Boolean.TRUE));

    JSLoaderModulesTracker jsLoaderModulesTracker = jsLoaderModulesServlet.getJSLoaderModulesTracker();

    ServiceReference<ServletContext> serviceReference = buildServiceReference("test", new Version("1.0.0"),
            true, 0, getResource("dependencies/config1.js"));

    jsLoaderModulesTracker.addingService(serviceReference);

    serviceReference = buildServiceReference("test", new Version("1.2.0"), true, 0,
            getResource("dependencies/config1.js"));

    jsLoaderModulesTracker.addingService(serviceReference);

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    jsLoaderModulesServlet.service(mockHttpServletRequest, mockHttpServletResponse);

    String content = mockHttpServletResponse.getContentAsString();

    content = content.replace('"', '\'');

    assertContains("'test': '/test-1.2.0'", content);
    assertContains("'test@1.2.0': '/test-1.2.0'", content);
    assertContains("'test@1.0.0': '/test-1.0.0'", content);
    assertContains("'test/some.es':{'dependencies':['exports','test@1.2.0/other.es']}", content);
    assertNotContains("'test/some.es':{'dependencies':['exports','test@1.0.0/other.es']}", content);
    assertContains("'test@1.2.0/some.es':{'dependencies':['exports'," + "'test@1.2.0/other.es']}", content);
    assertContains("'test@1.0.0/some.es':{'dependencies':['exports'," + "'test@1.0.0/other.es']}", content);
}

From source file:com.liferay.frontend.js.loader.modules.extender.internal.JSLoaderModulesServletTest.java

@Test
public void testMultipleModulesOutput() throws Exception {
    JSLoaderModulesServlet jsLoaderModulesServlet = buildJSLoaderModulesServlet(
            Collections.<String, Object>singletonMap("applyVersioning", Boolean.TRUE));

    JSLoaderModulesTracker jsLoaderModulesTracker = jsLoaderModulesServlet.getJSLoaderModulesTracker();

    ServiceReference<ServletContext> serviceReference = buildServiceReference("test", new Version("1.0.0"),
            true, 0, getResource("dependencies/config1.js"));

    jsLoaderModulesTracker.addingService(serviceReference);

    serviceReference = buildServiceReference("foo", new Version("13.2.23"), true, 0,
            getResource("dependencies/config2.js"));

    jsLoaderModulesTracker.addingService(serviceReference);

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    jsLoaderModulesServlet.service(mockHttpServletRequest, mockHttpServletResponse);

    String content = mockHttpServletResponse.getContentAsString();

    content = content.replace('"', '\'');

    assertContains("'test': '/test-1.0.0'", content);
    assertContains("'test@1.0.0': '/test-1.0.0'", content);
    assertContains("'test/some.es':{'dependencies':['exports','test@1.0.0/other.es']}", content);
    assertContains("'test@1.0.0/some.es':{'dependencies':['exports'," + "'test@1.0.0/other.es']}", content);
    assertContains("'foo': '/foo-13.2.23'", content);
    assertContains("'foo@13.2.23': '/foo-13.2.23'", content);
    assertContains(//  w  w  w. java2s. c  om
            "'foo/foo.es':{'dependencies':['exports','foo@13.2.23/fum.es'," + "'jquery@2.15.3/jquery.js']}",
            content);
    assertContains("'foo@13.2.23/foo.es':{'dependencies':['exports',"
            + "'foo@13.2.23/fum.es','jquery@2.15.3/jquery.js']}", content);
}

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

@Test
public void testHandleStores() throws Exception {
    RestRouterServlet servlet = new RestRouterServlet();
    servlet.setPathPrefix("/sports-api");
    servlet.setRestPackageRoot("com.doitnext.http.router.exampleclasses");
    servlet.setEndpointResolver(endpointResolver);
    servlet.setMethodInvoker(methodInvoker);
    servlet.setErrorHandler(errorHandler);
    servlet.setDynamicEndpointResolver(null);
    servlet.afterPropertiesSet();/* w w  w . j  a  va 2 s .  c om*/

    MockHttpServletRequest request;
    MockHttpServletResponse response;

    Object[][] testCases = { { "GET", "/mocker", "/sports-api/teams/favorites/user01/path/to/resource",
            "city=Atlanta", "application/json; model=hashmap", null, null, "user01", "path/to/resource" }, };

    for (Object[] testCase : testCases) {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        setUpRequest(testCase, request);
        servlet.handleRequest(request, response);
        String content = response.getContentAsString();
        System.out.println(content);
        Assert.assertEquals(200, response.getStatus());
        HashMap<String, String> t = new HashMap<String, String>();
        @SuppressWarnings("unchecked")
        Map<String, String> returnVal = objectMapper.readValue(content, t.getClass());
        Assert.assertEquals(testCase[7], returnVal.get("userId"));
        Assert.assertEquals(testCase[8], returnVal.get("storePath"));

    }
}

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

@Test
public void verifyOK() throws Exception {
    final AccessToken accessToken = mock(AccessToken.class);
    when(accessToken.getId()).thenReturn(TOKEN_ID);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(TOKEN_ID)).thenReturn(accessToken);
    when(centralOAuthService.revokeToken(accessToken)).thenReturn(true);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.REVOKE_URL);
    mockRequest.setParameter(OAuthConstants.TOKEN, TOKEN_ID);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//from  w  ww  .ja v a2 s.  c om
    assertEquals(HttpStatus.SC_NO_CONTENT, mockResponse.getStatus());
    assertNull(mockResponse.getContentType());
    assertEquals("null", mockResponse.getContentAsString());
}

From source file:it.geosolutions.httpproxy.service.BaseProxyServiceTest.java

/**
 * Test IProxyService execute as HTTP GET
 */// w  w  w . j a v a  2 s . co  m
public void executeGet() {
    try {
        // Generate mocked request and response
        MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "/proxy/");
        mockRequest.addParameter("url", testUrl);
        MockHttpServletResponse mockResponse = new MockHttpServletResponse();

        // Call proxy execute
        proxy.execute(mockRequest, mockResponse);

        // Assert the response
        assertNotNull(mockResponse);
        assertEquals(mockResponse.getStatus(), HttpStatus.SC_OK);
        assertNotNull(mockResponse.getOutputStream());
        assertNotNull(mockResponse.getContentType());
        assertTrue(mockResponse.getContentType().contains("text/xml"));

        LOGGER.info("Success proxy GET in '" + testUrl + "'");
        LOGGER.info("************************ Response ************************");
        LOGGER.info(mockResponse.getContentAsString());
        LOGGER.info("********************** EoF Response **********************");

    } catch (Exception e) {
        fail("Exception executing proxy");
    }
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrantType_withOpaqueTokens_preservesRefreshTokenExpiry() throws Exception {
    createClientAndUserInRandomZone();//from www.  j  a v a 2  s.  c om
    int refreshTokenValiditySeconds = 20;
    client.setRefreshTokenValiditySeconds(refreshTokenValiditySeconds);
    clientDetailsService.updateClientDetails(client, zone.getId());
    long firstGrantMillis = 1000L;
    when(timeService.getCurrentTimeMillis()).thenReturn(firstGrantMillis);
    CompositeToken tokenResponse = getTokensWithPasswordGrant(client.getClientId(), SECRET, user.getUserName(),
            SECRET, getZoneHostUrl(zone), "opaque");
    String firstRefreshToken = tokenResponse.getRefreshToken().getValue();

    long notYetExpiredTimeMillis = 5000L;
    when(timeService.getCurrentTimeMillis()).thenReturn(notYetExpiredTimeMillis);
    MockHttpServletResponse refreshResponse = useRefreshToken(firstRefreshToken, client.getClientId(), SECRET,
            getZoneHostUrl(zone));
    String secondRefreshToken = JsonUtils.readValue(refreshResponse.getContentAsString(), CompositeToken.class)
            .getRefreshToken().getValue();
    assertEquals(HttpStatus.SC_OK, refreshResponse.getStatus());

    long expiredTimeMillis = firstGrantMillis + refreshTokenValiditySeconds * 1000L + 1L;
    when(timeService.getCurrentTimeMillis()).thenReturn(expiredTimeMillis);
    MockHttpServletResponse expiredResponse = useRefreshToken(firstRefreshToken, client.getClientId(), SECRET,
            getZoneHostUrl(zone));
    assertEquals(HttpStatus.SC_UNAUTHORIZED, expiredResponse.getStatus());
    MockHttpServletResponse alsoExpiredResponse = useRefreshToken(secondRefreshToken, client.getClientId(),
            SECRET, getZoneHostUrl(zone));
    assertEquals(HttpStatus.SC_UNAUTHORIZED, alsoExpiredResponse.getStatus());
}

From source file:de.codecentric.boot.admin.zuul.filters.post.SendResponseFilterTests.java

private void runFilter(String characterEncoding, String content, boolean streamContent) throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    SendResponseFilter filter = createFilter(content, characterEncoding, response, streamContent);
    assertTrue("shouldFilter returned false", filter.shouldFilter());
    filter.run();//from www .j  a va2 s . c  o  m
    String encoding = RequestContext.getCurrentContext().getResponse().getCharacterEncoding();
    String expectedEncoding = characterEncoding != null ? characterEncoding
            : WebUtils.DEFAULT_CHARACTER_ENCODING;
    assertThat("wrong character encoding", encoding, equalTo(expectedEncoding));
    assertThat("wrong content", response.getContentAsString(), equalTo(content));
}

From source file:org.springframework.data.rest.tests.mongodb.MongoWebTests.java

@Test
public void testname2() throws Exception {

    Link usersLink = client.discoverUnique("users");
    Link userLink = assertHasContentLinkWithRel("self", client.request(usersLink));

    MockHttpServletResponse response = patchAndGet(userLink,
            "[{ \"op\": \"replace\", \"path\": \"/address/zipCode\", \"value\": \"ZIP\" },"
                    // + "{ \"op\": \"replace\", \"path\": \"/lastname\", \"value\": null }]", //
                    + "{ \"op\": \"remove\", \"path\": \"/lastname\" }]", //
            RestMediaTypes.JSON_PATCH_JSON);

    assertThat(JsonPath.read(response.getContentAsString(), "$.lastname"), is(nullValue()));
    assertThat(JsonPath.read(response.getContentAsString(), "$.address.zipCode"), is((Object) "ZIP"));
}