List of usage examples for org.springframework.mock.web MockHttpServletRequest setContentType
public void setContentType(@Nullable String contentType)
From source file:com.github.woonsan.katharsis.servlet.KatharsisFilterTest.java
@Test public void onSimpleResourceGetShouldReturnOneResource() throws Exception { MockFilterChain filterChain = new MockFilterChain(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setContextPath(""); request.setServletPath(null);/* w ww .j av a 2 s . c o m*/ request.setPathInfo(null); request.setRequestURI("/api/tasks/1"); request.setContentType(JsonApiMediaType.APPLICATION_JSON_API); request.addHeader("Accept", "*/*"); request.addParameter("filter", ""); MockHttpServletResponse response = new MockHttpServletResponse(); katharsisFilter.doFilter(request, response, filterChain); String responseContent = response.getContentAsString(); log.debug("responseContent: {}", responseContent); assertNotNull(responseContent); assertJsonPartEquals("tasks", responseContent, "data.type"); assertJsonPartEquals("\"1\"", responseContent, "data.id"); assertJsonPartEquals(SOME_TASK_ATTRIBUTES, responseContent, "data.attributes"); assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data.links"); assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links"); assertJsonPartEquals("[]", responseContent, "included"); }
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);//ww w. ja va 2 s .co m 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:org.opennms.netmgt.ncs.rest.AbstractSpringJerseyRestTestCase.java
protected void putXmlObject(JAXBContext context, String url, int expectedStatus, Object object) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(object, out);// www.j ava 2 s . c o m byte[] content = out.toByteArray(); MockHttpServletRequest request = createRequest(PUT, url); request.setContentType(MediaType.APPLICATION_XML); request.setContent(content); MockHttpServletResponse response = createResponse(); dispatch(request, response); assertEquals(expectedStatus, response.getStatus()); }
From source file:org.opennms.netmgt.ncs.rest.AbstractSpringJerseyRestTestCase.java
protected void sendData(String requestType, String contentType, String url, String data, int statusCode) throws Exception { MockHttpServletRequest request = createRequest(requestType, url); request.setContentType(contentType); if (contentType.equals(MediaType.APPLICATION_FORM_URLENCODED)) { request.setParameters(parseParamData(data)); request.setContent(new byte[] {}); } else {//from w w w .j a v a2 s . c om request.setContent(data.getBytes()); } final MockHttpServletResponse response = createResponse(); dispatch(request, response); s_log.info("Received response: {}", stringifyResponse(response)); assertEquals(response.getErrorMessage(), statusCode, response.getStatus()); }
From source file:org.openmrs.web.controller.form.FormFormControllerTest.java
@Test public void shouldNotSaveAFormWhenFormsAreLocked() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/admin/forms/formEdit.form?formId=1"); request.setSession(new MockHttpSession(null)); HttpServletResponse response = new MockHttpServletResponse(); controller.handleRequest(request, response); request.addParameter("name", "TRUNK"); request.addParameter("version", "1"); request.addParameter("action", "Form.save"); request.setContentType("application/x-www-form-urlencoded"); ModelAndView mav = controller.handleRequest(request, response); Assert.assertEquals("The save attempt should have failed!", "index.htm", mav.getViewName()); Assert.assertNotEquals("formEdit.form", mav.getViewName()); Assert.assertSame(controller.getFormView(), mav.getViewName()); Assert.assertNotNull(formService.getForm(1)); }
From source file:org.openmrs.web.controller.form.FormFormControllerTest.java
@Test public void shouldNotDuplicateAFormWhenFormsAreLocked() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/admin/forms/formEdit.form?duplicate=true&formId=1"); request.setSession(new MockHttpSession(null)); HttpServletResponse response = new MockHttpServletResponse(); controller.handleRequest(request, response); request.addParameter("name", "TRUNK"); request.addParameter("version", "1"); request.addParameter("action", "Form.Duplicate"); request.setContentType("application/x-www-form-urlencoded"); ModelAndView mav = controller.handleRequest(request, response); Assert.assertEquals("The duplicate attempt should have failed!", "index.htm", mav.getViewName()); Assert.assertNotEquals("formEdit.form", mav.getViewName()); Assert.assertSame(controller.getFormView(), mav.getViewName()); Assert.assertNotNull(formService.getForm(1)); }
From source file:org.cateproject.test.functional.mockmvc.HtmlUnitRequestBuilder.java
private void contentType(MockHttpServletRequest result) { String contentType = header("Content-Type"); result.setContentType(contentType == null ? MediaType.ALL_VALUE.toString() : contentType); }
From source file:com.doitnext.http.router.DefaultInvokerTest.java
private HttpServletRequest createHappyMockRequest(HttpMethod method, PathMatch pm) throws JsonGenerationException, JsonMappingException, IOException { MockHttpServletRequest req = new MockHttpServletRequest(); req.setMethod(method.name());//from ww w . j av a2s. co m if (method == HttpMethod.POST || method == HttpMethod.PUT) { TestTeamPojo pojo = createRandomPojo(); req.setContentType("application/json"); req.setContent(mapper.writeValueAsBytes(pojo)); } String terminus = pm.getMatchedPath().getTerminus(); if (!StringUtils.isEmpty(terminus)) { req.setQueryString(terminus); String parts[] = req.getQueryString().split("&"); for (String part : parts) { if (!StringUtils.isEmpty(part)) { String pieces[] = part.split("="); if (!StringUtils.isEmpty(pieces[0])) { String key = pieces[0]; String value = ""; if (pieces.length > 1) { value = pieces[1].trim(); } req.addParameter(key, value); } } } } return req; }
From source file:org.pentaho.platform.dataaccess.datasource.wizard.csv.FileUploadServiceTest.java
@Test public void testUpload() throws Exception { PentahoSystemHelper.init();/*from w w w. j ava 2 s . c o m*/ StandaloneSession pSession = new StandaloneSession("12345678901234567890"); PentahoSessionHolder.setSession(pSession); UUID uuid = UUIDUtil.getUUID(); String fileName = uuid.toString(); MockHttpSession session = new MockHttpSession(null, "12345678901234567890"); //$NON-NLS-1$ MockHttpServletRequest request = new MockHttpServletRequest("POST", ""); //$NON-NLS-1$ //$NON-NLS-2$ request.setSession(session); request.addParameter("file_name", fileName); //$NON-NLS-1$ request.addParameter("mark_temporary", "true"); //$NON-NLS-1$ //$NON-NLS-2$ request.setContentType("multipart/form-data; boundary=boundary"); //$NON-NLS-1$ StringBuffer content = new StringBuffer(); content.append("--boundary\r\n"); //$NON-NLS-1$ content.append( "Content-Disposition: form-data; name=uploadFormElement; filename=test_file.csv\r\nContent-Type: multipart/form-data\r\n\r\n"); //$NON-NLS-1$ content.append("REGIONC,NWEIGHT,HD65,xdate,Location,charlen,xfactor,Flag\r\n"); //$NON-NLS-1$ content.append("3,25677.96525,1231,1/1/10,Afghanistan,11,111.9090909,0\r\n"); //$NON-NLS-1$ content.append("4,24261.81026,1663,1/2/10,Albania,7,237.5714286,0\r\n"); //$NON-NLS-1$ content.append("2,31806.29502,5221,1/3/10,Algeria,7,745.8571429,1\r\n");//$NON-NLS-1$ content.append("4,22345.39749,5261,1/4/10,American Samoa,14,375.7857143,1\r\n");//$NON-NLS-1$ content.append("4,22345.39749,5261,1/4/10,American Samoa,14,375.7857143,1\r\n");//$NON-NLS-1$ content.append("3,25677.96525,1231,1/1/10,Afghanistan,11,111.9090909,0\r\n");//$NON-NLS-1$ content.append("4,24261.81026,1663,1/2/10,Albania,7,237.5714286,0\r\n");//$NON-NLS-1$ content.append("2,31806.29502,5221,1/3/10,Algeria,7,745.8571429,1\r\n");//$NON-NLS-1$ content.append("4,22345.39749,5261,1/4/10,American Samoa,14,375.7857143,1\r\n");//$NON-NLS-1$ content.append("--boundary--\r\n"); //$NON-NLS-1$ request.setContent(content.toString().getBytes()); UploadFileDebugServlet uploadServlet = new UploadFileDebugServlet(); MockHttpServletResponse response = new MockHttpServletResponse(); uploadServlet.service(request, response); response.getWriter().flush(); response.getWriter().close(); fileName = response.getContentAsString(); String path = PentahoSystem.getApplicationContext().getSolutionPath(TMP_FILE_PATH); String filenameWithPath = path + File.separatorChar + fileName; File file = new File(filenameWithPath); assertTrue(file.exists()); if (file.exists()) { file.delete(); } }
From source file:cc.redpen.server.api.RedPenResourceTest.java
private MockHttpServletRequest constructMockRequest(String method, String requestURI, String acceptHeader, String contentType) {/* www . j a v a 2 s . c o m*/ MockHttpServletRequest mockRequest = new MockHttpServletRequest() { public String getPathTranslated() { return null; // prevent Spring to resolve the file on the filesystem which fails } @Override public <T extends HttpUpgradeHandler> T upgrade(Class<T> aClass) throws IOException, ServletException { return null; } }; mockRequest.setMethod(method); mockRequest.setRequestURI(requestURI); mockRequest.setServerPort(8080); mockRequest.addHeader("Accept", acceptHeader); mockRequest.addHeader("Content-Type", contentType); mockRequest.setContentType(contentType); return mockRequest; }