Java Code Examples for org.springframework.mock.web.MockHttpServletResponse#getContentAsString()

The following examples show how to use org.springframework.mock.web.MockHttpServletResponse#getContentAsString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ServletUrlProviderTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceUrl() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks/");
	request.setRequestURI("/api/tasks/");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	request.addHeader("Accept", "*/*");

	MockHttpServletResponse response = new MockHttpServletResponse();

	katharsisServlet.service(request, response);

	String responseContent = response.getContentAsString();

	log.debug("responseContent: {}", responseContent);
	assertNotNull(responseContent);
	assertJsonPartEquals("tasks", responseContent, "data[0].type");
	assertJsonPartEquals("\"1\"", responseContent, "data[0].id");

	// check url
	assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data[0].links");
}
 
Example 2
Source File: FileControllerTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
/**
 * test open Sender transport
 *
 * @throws Exception Exception
 */
@Test
public void testSenderExist() throws Exception {
    String content = "{\"brokerId\":\"" + this.brokerIdMap.get("brokerId")
            + "\",\"groupId\":\"" + this.defaultGroupId
            + "\",\"topicName\":\"" + this.senderTransport
            + "\",\"role\":\"0\",\"overWrite\":\"1\"}";

    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/file/openTransport").contentType(MediaType.APPLICATION_JSON_UTF8).content(content).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token)).andReturn();
    MockHttpServletResponse response = mvcResult.getResponse();
    String result = response.getContentAsString();
    Map<String, String> map = JsonHelper.json2Object(result, new TypeReference<Map<String, String>>() {
    });

    Assert.assertEquals(String.valueOf(ErrorCode.TRANSPORT_ALREADY_EXISTS.getCode()), map.get("code"));
}
 
Example 3
Source File: FileControllerTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
/**
 * test list transport
 *
 * @throws Exception Exception
 */
@Test
@SuppressWarnings("unchecked")
public void testListTransport() throws Exception {
    String url = "/file/listTransport?brokerId=" + brokerIdMap.get("brokerId") + "&groupId=" + this.defaultGroupId;

    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON_UTF8).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token)).andReturn();
    MockHttpServletResponse response = mvcResult.getResponse();
    String result = response.getContentAsString();
    Assert.assertNotNull(result);
    GovernanceResult governanceResult = JsonHelper.json2Object(result, GovernanceResult.class);
    Assert.assertEquals(200, (int) governanceResult.getStatus());
    List<FileTransportEntity> transportList = (List<FileTransportEntity>) governanceResult.getData();
    Assert.assertNotNull(transportList);
    Assert.assertTrue(transportList.size() > 0);
}
 
Example 4
Source File: ConfigViewTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testRender() throws Exception {

	ConfigView configView = ConfigView.getInstance();

	Model configData = new LinkedHashModelFactory().createEmptyModel();
	configData.add(RDF.ALT, RDF.TYPE, RDFS.CLASS);

	Map<Object, Object> map = new LinkedHashMap<>();
	map.put(ConfigView.HEADERS_ONLY, false);
	map.put(ConfigView.CONFIG_DATA_KEY, configData);
	map.put(ConfigView.FORMAT_KEY, RDFFormat.NTRIPLES);

	final MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod(HttpMethod.GET.name());
	request.addHeader("Accept", RDFFormat.NTRIPLES.getDefaultMIMEType());

	MockHttpServletResponse response = new MockHttpServletResponse();

	configView.render(map, request, response);

	String ntriplesData = response.getContentAsString();
	Model renderedData = Rio.parse(new StringReader(ntriplesData), "", RDFFormat.NTRIPLES);
	assertThat(renderedData).isNotEmpty();
}
 
Example 5
Source File: SwaggerJsonTest.java    From alcor with Apache License 2.0 6 votes vote down vote up
@Test
public void createSpringfoxSwaggerJson() throws Exception{
    String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andReturn();
    
    MockHttpServletResponse response = mvcResult.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try(BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
        writer.write(swaggerJson);
    }

    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
        .withGeneratedExamples()
        .withInterDocumentCrossReferences()
        .build();
    Swagger2MarkupConverter.from(Paths.get(outputDir,"swagger.json"))
        .withConfig(config)
        .build()
        .toFile(Paths.get(outputDir, "swagger"));
}
 
Example 6
Source File: SwaggerJsonTest.java    From alcor with Apache License 2.0 6 votes vote down vote up
@Test
public void createSpringfoxSwaggerJson() throws Exception{
    String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try(BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
        writer.write(swaggerJson);
    }

    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
            .withGeneratedExamples()
            .withInterDocumentCrossReferences()
            .build();
    Swagger2MarkupConverter.from(Paths.get(outputDir,"swagger.json"))
            .withConfig(config)
            .build()
            .toFile(Paths.get(outputDir, "swagger"));
}
 
Example 7
Source File: SampleKatharsisServletTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testKatharsisInclude() throws Exception {

	Node root = new Node(1L, null, null);
	Node child1 = new Node(2L, root, Collections.<Node>emptySet());
	Node child2 = new Node(3L, root, Collections.<Node>emptySet());
	root.setChildren(new LinkedHashSet<>(Arrays.asList(child1, child2)));
	nodeRepository.save(root);
	nodeRepository.save(child1);
	nodeRepository.save(child2);
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setServletPath("/api");
	request.setPathInfo("/nodes/1");
	request.setRequestURI("/api/nodes/1");
	request.setQueryString("include[nodes]=parent");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	Map<String, String> params = new HashMap<>();
	params.put("include[nodes]", "children");
	request.setParameters(params);
	request.addHeader("Accept", "*/*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	katharsisServlet.service(request, response);
	String responseContent = response.getContentAsString();
	assertTopLevelNodesCorrectWithChildren(responseContent);
}
 
Example 8
Source File: Saml10SuccessResponseViewTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyResponse() throws Exception {
    final Map<String, Object> model = new HashMap<>();

    final Map<String, Object> attributes = new HashMap<>();
    attributes.put("testAttribute", "testValue");
    attributes.put("testEmptyCollection", Collections.emptyList());
    attributes.put("testAttributeCollection", Arrays.asList("tac1", "tac2"));
    final Principal principal = new DefaultPrincipalFactory().createPrincipal("testPrincipal", attributes);

    final Map<String, Object> authAttributes = new HashMap<>();
    authAttributes.put(
            SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD,
            SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT);
    authAttributes.put("testSamlAttribute", "value");

    final Authentication primary = TestUtils.getAuthentication(principal, authAttributes);
    final Assertion assertion = new ImmutableAssertion(
            primary, Collections.singletonList(primary), TestUtils.getService(), true);
    model.put("assertion", assertion);

    final MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse);
    final String written = servletResponse.getContentAsString();

    assertTrue(written.contains("testPrincipal"));
    assertTrue(written.contains("testAttribute"));
    assertTrue(written.contains("testValue"));
    assertFalse(written.contains("testEmptyCollection"));
    assertTrue(written.contains("testAttributeCollection"));
    assertTrue(written.contains("tac1"));
    assertTrue(written.contains("tac2"));
    assertTrue(written.contains(SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT));
    assertTrue(written.contains("AuthenticationMethod"));
    assertTrue(written.contains("AssertionID"));
}
 
Example 9
Source File: JsonViewTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldReturnOutputWithoutWhitespaceThatIsNotAllowedInHeaders() throws Exception {
    JsonView view = new JsonView(requestContext);
    MockHttpServletResponse response = new MockHttpServletResponse();
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("key", "\r\t\n");
    view.renderMergedOutputModel(asMap(map), new MockHttpServletRequest(), response);
    String json = response.getContentAsString();
    assertThatJson("{\n  \"key\": \"\\r\\t\\n\"\n}").isEqualTo(json);
}
 
Example 10
Source File: AbstractAlfrescoMvcTest.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
@Test
public void when_alfrescoRestSerializationIsUsedButMocked_expect_okAndNodrefNotSerialized() throws Exception {
	MockHttpServletResponse res = mockWebscript.withControllerMapping("test/noderefAlfrescoResponse").execute();
	Assertions.assertEquals(HttpStatus.OK.value(), res.getStatus());

	// the response has been changed in the advice
	String contentAsString = res.getContentAsString();

	// TODO: since a mock is being used for webscriptHelper and if the response i
	// correctly processed by AlfrescoApiResponseInterceptor
	// there will always be an empty string unless we do something more to handle
	// this (so it is expected as is)
	Assertions.assertEquals("", contentAsString);
	Assertions.assertEquals("true", res.getHeader("TEST_ADVICE_APPLIED"));
}
 
Example 11
Source File: Saml10SuccessResponseViewTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyResponseWithoutAuthMethod() throws Exception {
    final Map<String, Object> model = new HashMap<>();

    final Map<String, Object> attributes = new HashMap<>();
    attributes.put("testAttribute", "testValue");
    final Principal principal = new DefaultPrincipalFactory().createPrincipal("testPrincipal", attributes);

    final Map<String, Object> authnAttributes = new HashMap<>();
    authnAttributes.put("authnAttribute1", "authnAttrbuteV1");
    authnAttributes.put("authnAttribute2", "authnAttrbuteV2");
    authnAttributes.put(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME, Boolean.TRUE);

    final Authentication primary = TestUtils.getAuthentication(principal, authnAttributes);

    final Assertion assertion = new ImmutableAssertion(
            primary, Collections.singletonList(primary), TestUtils.getService(), true);
    model.put("assertion", assertion);

    final MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse);
    final String written = servletResponse.getContentAsString();

    assertTrue(written.contains("testPrincipal"));
    assertTrue(written.contains("testAttribute"));
    assertTrue(written.contains("testValue"));
    assertTrue(written.contains("authnAttribute1"));
    assertTrue(written.contains("authnAttribute2"));
    assertTrue(written.contains(CasProtocolConstants.VALIDATION_REMEMBER_ME_ATTRIBUTE_NAME));
    assertTrue(written.contains("urn:oasis:names:tc:SAML:1.0:am:unspecified"));
}
 
Example 12
Source File: TopicControllerTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testTopicClose() throws Exception {
    String url = "/topic/close?brokerId=" + brokerIdMap.get("brokerId") + "&topic=com.weevent.rest&groupId=1";
    MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON_UTF8).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token))
            .andReturn().getResponse();
    Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK);
    String contentAsString = response.getContentAsString();
    Assert.assertEquals(Boolean.valueOf(contentAsString), true);
}
 
Example 13
Source File: WebAppContextConfigurationTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void loadServices() throws Exception {
    final MockHttpServletResponse response = this.mvc.perform(get("/getServices.html"))
            .andExpect(status().isOk())
            .andReturn().getResponse();

    final String resp = response.getContentAsString();
    assertTrue(resp.contains("services"));
    assertTrue(resp.contains("status"));
}
 
Example 14
Source File: SampleKatharsisServletTest.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testKatharsisIncludeNestedWithDefault() throws Exception {
	Node root = new Node(1L, null, null);
	Locale engLocale = new Locale(1L, java.util.Locale.ENGLISH);
	Node child1 = new Node(2L, root, Collections.<Node>emptySet());
	NodeComment child1Comment = new NodeComment(1L, "Child 1", child1, engLocale);
	child1.setNodeComments(new LinkedHashSet<>(Collections.singleton(child1Comment)));
	Node child2 = new Node(3L, root, Collections.<Node>emptySet(), Collections.<NodeComment>emptySet());
	root.setChildren(new LinkedHashSet<>(Arrays.asList(child1, child2)));
	nodeRepository.save(root);
	nodeRepository.save(child1);
	nodeRepository.save(child2);

	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setServletPath("/api");
	request.setPathInfo("/nodes/1");
	request.setRequestURI("/api/nodes/1");
	request.setQueryString("include[nodes]=children.nodeComments");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	Map<String, String> params = new HashMap<>();
	params.put("include[nodes]", "children.nodeComments.langLocale");
	request.setParameters(params);
	request.addHeader("Accept", "*/*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	katharsisServlet.service(request, response);
	String responseContent = response.getContentAsString();
	assertTopLevelNodesCorrectWithChildren(responseContent);
}
 
Example 15
Source File: DispatcherWebscriptSpringAnnotationEnableTest.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
@Test
public void when_alfrescoMvcSerializationIsUsed_expect_okAndNodrefFullySerialized() throws Exception {
	// the config is correct uses
	// org.alfresco.rest.framework.jacksonextensions.RestJsonModule so we have to
	// change the response
	// format expectation due to different serializers

	MockHttpServletResponse res = mockWebscript.withControllerMapping("test/noderef").execute();
	Assertions.assertEquals(HttpStatus.OK.value(), res.getStatus());

	String contentAsString = res.getContentAsString();
	Assertions.assertEquals("\"b\"", contentAsString);
}
 
Example 16
Source File: RequestUtil.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public static String sendRequest(WebApplicationContext webApplicationContext,String requestType, String uriWithParam, String ...requestJsons) throws Exception {
    MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    MockHttpServletResponse mockResponse =null;
    if(ConstantsForTest.POST.equals(requestType)){
        if(requestJsons.length > 0){
            mockResponse =sendPost(mockMvc,uriWithParam,requestJsons[0]);
        }else{
            mockResponse =sendPost(mockMvc,uriWithParam,"");
        }
    }else if(ConstantsForTest.GET.equals(requestType)){
        HttpHeaders httpHeaders=getHeaders(webApplicationContext);
        Cookie cookies =getCookies(webApplicationContext);
        MockHttpSession session=getSession(webApplicationContext);
        mockResponse =sendGet(mockMvc,httpHeaders,cookies,session,uriWithParam);
    }else if(ConstantsForTest.PUT.equals(requestType)){
        if(requestJsons.length > 0){
            mockResponse =sendPut(mockMvc,uriWithParam,requestJsons[0]);
        }
    }
    int status = mockResponse.getStatus();
    String uri = "";
    if (uriWithParam.indexOf(ConstantsForTest.QuestionMark) > 0) {
        uri = uriWithParam.substring(0, uriWithParam.indexOf(ConstantsForTest.QuestionMark));
    } else {
        uri = uriWithParam;
    }
    if (status != 200) {
        LOGGER.error(MessageUtil.getFailureString(uri, status));
        throw new RuntimeException(MessageUtil.getFailureString(uri, status));
    }
    String res = mockResponse.getContentAsString();
    System.out.println(MessageUtil.getSuccessString(uri, res));
    LOGGER.info(MessageUtil.getSuccessString(uri, res));
    return res;
}
 
Example 17
Source File: BrokerControllerTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void getBrokerByBrokerId() throws Exception {
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/broker/" + this.brokerIdMap.get("brokerId")).contentType(MediaType.APPLICATION_JSON_UTF8).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token)).andReturn();
    MockHttpServletResponse response = mvcResult.getResponse();
    Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK);
    String contentAsString = response.getContentAsString();
    Assert.assertNotNull(contentAsString);
}
 
Example 18
Source File: XmlUtil.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static Document getStringResponseAsDoc(MockHttpServletResponse response) throws JDOMException, IOException {

    SAXBuilder sb = new SAXBuilder();
    String strResponse = response.getContentAsString();
    return sb.build(new ByteArrayInputStream(strResponse.getBytes(response.getCharacterEncoding())));
  }
 
Example 19
Source File: Swagger2MarkupTest.java    From SpringBootBucket with MIT License 4 votes vote down vote up
/**
     * 自动生成adoc文件
     * @throws Exception e
     *
     * 执行完成后生成PDF文件方法:
     *
     * 首先在`swagger/swagger.adoc`的顶部加入:
    ```
    :toclevels: 3
    :numbered:
    ```
    注意有个空行分割,目的是左边导航菜单是3级,并且自动加序号。
    为了美化显示,还要将`swagger.adoc`中全局替换一下,将
    ```
    cols=".^2,.^3,.^9,.^4,.^2"
    ```
    替换成:
    ```
    cols=".^2,.^3,.^6,.^4,.^5"
    ```
    然后在/resources目录下面执行:
    ```
    asciidoctor-pdf -r asciidoctor-pdf-cjk-kai_gen_gothic -a pdf-style=KaiGenGothicCN swagger/swagger.adoc
    ```
    会在`swagger.adoc`的同级目录生成`swagger.pdf`文件。
     */
    @Test
    public void createSpringFoxSwaggerJson() throws Exception {
//        String outputDir = System.getProperty("swaggerOutputDir"); // mvn test
        MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();
        String swaggerJson = response.getContentAsString();
//        Files.createDirectories(Paths.get(outputDir));
//        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
//            writer.write(swaggerJson);
//        }
        LOG.info("--------------------swaggerJson create --------------------");
        convertAsciidoc(swaggerJson);
        LOG.info("--------------------swagon.json to asciiDoc finished --------------------");
    }
 
Example 20
Source File: ServletResponseResultWriterTest.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
private String writeToResponse(Object value) throws IOException {
  MockHttpServletResponse response = new MockHttpServletResponse();
  ServletResponseResultWriter writer = new ServletResponseResultWriter(response, null);
  writer.write(value);
  return response.getContentAsString();
}