Java Code Examples for org.springframework.test.web.servlet.MvcResult#getResponse()
The following examples show how to use
org.springframework.test.web.servlet.MvcResult#getResponse() .
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: SwaggerJsonTest.java From alcor with Apache License 2.0 | 6 votes |
@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 2
Source File: TestPointFCsubsetting.java From tds with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void getSubsettedData() throws Exception { // problem is that browser wont display text/csv in line, so use tesxt/plain; see thredds.server.ncss.view // .dsg.PointWriter.WriterCSV String expectFormat = (format == SupportedFormat.CSV_STREAM) ? ContentType.text.getContentHeader() : format.getMimeType(); RequestBuilder rb = MockMvcRequestBuilders.get(dataset + req + format.getFormatName()).servletPath(dataset); System.out.printf("%nURL='%s'%n", dataset + req + format.getFormatName()); MvcResult result = this.mockMvc.perform(rb).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(expectFormat)).andReturn(); MockHttpServletResponse response = result.getResponse(); System.out.printf("getSubsettedData format=%s status = %d type=%s%n", format, response.getStatus(), response.getContentType()); }
Example 3
Source File: SwaggerJsonTest.java From alcor with Apache License 2.0 | 6 votes |
@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 4
Source File: SwaggerJsonTest.java From alcor with Apache License 2.0 | 6 votes |
@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 5
Source File: FileControllerTest.java From WeEvent with Apache License 2.0 | 6 votes |
private void closeTransport() throws Exception { String contentSender = "{\"brokerId\":\"" + this.brokerIdMap.get("brokerId") + "\",\"groupId\":\"" + this.defaultGroupId + "\",\"topicName\":\"" + this.senderTransport + "\"}"; MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/file/closeTransport").contentType(MediaType.APPLICATION_JSON_UTF8).content(contentSender).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); Boolean isSuccess = (Boolean) governanceResult.getData(); Assert.assertTrue(isSuccess); String contentReceiver = "{\"brokerId\":\"" + this.brokerIdMap.get("brokerId") + "\",\"groupId\":\"" + this.defaultGroupId + "\",\"topicName\":\"" + this.receiverTransport + "\"}"; mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/file/closeTransport").contentType(MediaType.APPLICATION_JSON_UTF8).content(contentReceiver).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token)).andReturn(); response = mvcResult.getResponse(); result = response.getContentAsString(); Assert.assertNotNull(result); governanceResult = JsonHelper.json2Object(result, GovernanceResult.class); isSuccess = (Boolean) governanceResult.getData(); Assert.assertTrue(isSuccess); }
Example 6
Source File: FileControllerTest.java From WeEvent with Apache License 2.0 | 6 votes |
/** * test prepareUploadFile * * @throws Exception Exception */ @Test public void testPrepareUploadFile() throws Exception { String fileId = UUID.randomUUID().toString().replace("-", ""); String url = "/file/upload?groupId=" + this.defaultGroupId + "&identifier=" + fileId + "&topicName=" + this.senderTransport + "&totalChunks=" + 10 + "&totalSize=" + 10485760 + "&chunkSize=" + 1048576 + "&filename=test.txt"; MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(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()); String rootPath = System.getProperty("user.dir") + File.separator; String filePath = rootPath + "logs" + File.separator + "upload" + File.separator + fileId; Assert.assertTrue(Utils.removeLocalFile(filePath)); }
Example 7
Source File: SwaggerJsonTest.java From alcor with Apache License 2.0 | 6 votes |
@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 8
Source File: Swagger2MarkupTest.java From springrestdoc with MIT License | 6 votes |
@Test public void createJsonFileFromSwaggerEndpoint() throws Exception { String outputDir = Optional.ofNullable(System.getProperty("io.springfox.staticdocs.outputDir")) .orElse("build/swagger"); System.err.println(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); } }
Example 9
Source File: InvestorControllerTest.java From Hands-On-RESTful-API-Design-Patterns-and-Best-Practices with MIT License | 5 votes |
@Test public void fetchAllInvestors() throws Exception{ RequestBuilder requestBuilder = MockMvcRequestBuilders.get( "/investors").accept( MediaType.APPLICATION_JSON); MvcResult result = mockMvc.perform(requestBuilder).andReturn(); MockHttpServletResponse response = result.getResponse(); System.out.println("here "+response); }
Example 10
Source File: XpathResultMatchers.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Evaluate the XPath and assert that content doesn't exist. */ public ResultMatcher doesNotExist() { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { MockHttpServletResponse response = result.getResponse(); xpathHelper.doesNotExist(response.getContentAsByteArray(), getDefinedEncoding(response)); } }; }
Example 11
Source File: XpathResultMatchers.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Evaluate the XPath and assert that content exists. */ public ResultMatcher exists() { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { MockHttpServletResponse response = result.getResponse(); xpathHelper.exists(response.getContentAsByteArray(), getDefinedEncoding(response)); } }; }
Example 12
Source File: SpringMockRamlMessageTest.java From raml-tester with Apache License 2.0 | 5 votes |
@Test public void simple() throws Exception { final MvcResult result = mockMvc.perform(get("http://test.com/path?param=val") .characterEncoding("utf-8") .content("contentä") .contentType(MediaType.TEXT_PLAIN) .param("param2", "val2") .header("head", "hval")).andReturn(); final SpringMockRamlRequest ramlRequest = new SpringMockRamlRequest(result.getRequest()); assertEquals("contentä", new String(ramlRequest.getContent(), "utf-8")); assertEquals("text/plain", ramlRequest.getContentType()); final Values formValues = new Values().addValue("param", "val").addValue("param2", "val2"); assertEquals(formValues, ramlRequest.getFormValues()); final Values headerValues = new Values().addValue("head", "hval").addValue("Content-Type", "text/plain;charset=utf-8"); assertEquals(headerValues, ramlRequest.getHeaderValues()); assertEquals("GET", ramlRequest.getMethod()); assertEquals(new Values().addValue("param", "val"), ramlRequest.getQueryValues()); assertEquals("http://test.com/path", ramlRequest.getRequestUrl(null, false)); assertEquals("http://x.y/path", ramlRequest.getRequestUrl("http://x.y", false)); final SpringMockRamlResponse ramlResponse = new SpringMockRamlResponse(result.getResponse()); assertEquals("responsö", new String(ramlResponse.getContent(), "iso-8859-1")); assertEquals("text/dummy;charset=ISO-8859-1", ramlResponse.getContentType()); final Values resHeaderValues = new Values() .addValue("head", "resValue") .addValue("Content-Length", Integer.toString("responsö".length())) .addValue("Content-Type", "text/dummy;charset=ISO-8859-1"); assertEquals(resHeaderValues, ramlResponse.getHeaderValues()); assertEquals(202, ramlResponse.getStatus()); }
Example 13
Source File: AccountControllerTest.java From WeEvent with Apache License 2.0 | 5 votes |
@Test public void testAccountList() throws Exception { String token = createToken(); Security.setProperty(token, "1"); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/user/accountList").contentType(MediaType.APPLICATION_JSON_UTF8).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token)) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK); Assert.assertTrue(response.getContentAsString().contains("200")); }
Example 14
Source File: AccountControllerTest.java From WeEvent with Apache License 2.0 | 5 votes |
@Test public void testAuthRequire() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/user/require").contentType(MediaType.APPLICATION_JSON_UTF8)).andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK); Map jsonObject = JsonHelper.json2Object(response.getContentAsString(), Map.class); Assert.assertNotNull(jsonObject); Assert.assertEquals(jsonObject.get("code").toString(), "302000"); }
Example 15
Source File: InvestorControllerTest.java From Hands-On-RESTful-API-Design-Patterns-and-Best-Practices with MIT License | 5 votes |
@Test public void fetchAllInvestors() throws Exception{ RequestBuilder requestBuilder = MockMvcRequestBuilders.get( "/investors").accept( MediaType.APPLICATION_JSON); MvcResult result = mockMvc.perform(requestBuilder).andReturn(); MockHttpServletResponse response = result.getResponse(); System.out.println("here "+response); }
Example 16
Source File: TopicHistoricalTest.java From WeEvent with Apache License 2.0 | 5 votes |
@Test public void testInsertHistoricalData() throws Exception { String content = "{\"brokerId\":1,\"groupId\":\"1\",\"weevent\":{\"eventId\":\"1\",\"extensions\":{},\"topic\":\"com.weevent.rest\"}}"; MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/historicalData/insertHistoricalData") .contentType(MediaType.APPLICATION_JSON_UTF8).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token).content(content)).andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String result = response.getContentAsString(); Assert.assertNotNull(result); }
Example 17
Source File: XpathResultMatchers.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Evaluate the XPath and assert the number of nodes found with the given * Hamcrest {@link Matcher}. */ public ResultMatcher nodeCount(final Matcher<Integer> matcher) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { MockHttpServletResponse response = result.getResponse(); xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), matcher); } }; }
Example 18
Source File: AccountControllerTest.java From WeEvent with Apache License 2.0 | 5 votes |
@Test public void testUpdatePasswordException003() throws Exception { String content = "{\"username\":\"zjy05\",\"oldPassword\":\"\",\"password\":\"\"}"; MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/user/update").contentType(MediaType.APPLICATION_JSON_UTF8).content(content)) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK); GovernanceResult governanceResult = JsonHelper.json2Object(response.getContentAsString(), GovernanceResult.class); Assert.assertEquals("400", governanceResult.getStatus().toString()); }
Example 19
Source File: UserAccountControllerTest.java From Building-Web-Apps-with-Spring-5-and-Angular with MIT License | 5 votes |
@Test @DisplayName("Should return error message for when user not existing in the database tries to login.") public void Should_ReturnErrorMessage_ForUnmatchingUser() throws Exception { User user = new User(); user.setEmail("[email protected]"); user.setPassword("foobar"); // // Create JSON Representation for User object; // Gson is a Java serialization/deserialization library to // convert Java Objects into JSON and back // Gson gson = new Gson(); String jsonUser = gson.toJson(user); // // Mock the isValidUser method of userService // Mockito.when(this.userService.isValidUser("[email protected]", "foobar")).thenReturn(null); // // Invoke the method // MvcResult result = this.mockMvc.perform( post("/account/login/process") .contentType(MediaType.APPLICATION_JSON) .content(jsonUser)) .andExpect(status().isOk()) .andReturn(); MockHttpServletResponse response = result.getResponse(); ObjectMapper mapper = new ObjectMapper(); ExecutionStatus responseObj = mapper.readValue(response.getContentAsString(), ExecutionStatus.class); assertTrue(responseObj.getCode().equals("USER_LOGIN_UNSUCCESSFUL")); assertTrue(responseObj.getMessage().equals("Username or password is incorrect. Please try again!")); }
Example 20
Source File: MyResultHandler.java From springrestdoc with MIT License | 4 votes |
@Override public void handle(MvcResult result) throws Exception { MockHttpServletRequest request = result.getRequest(); MockHttpServletResponse response = result.getResponse(); logger.error("HTTP method: {}, status code: {}", request.getMethod(), response.getStatus()); }