List of usage examples for org.springframework.mock.web MockHttpServletRequest setMethod
public void setMethod(@Nullable String method)
From source file:alfio.controller.ReservationFlowIntegrationTest.java
private String reserveTicket(String eventName) { ReservationForm reservationForm = new ReservationForm(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("POST"); ServletWebRequest servletWebRequest = new ServletWebRequest(request); BindingResult bindingResult = new BeanPropertyBindingResult(reservationForm, "reservation"); Model model = new BindingAwareModelMap(); RedirectAttributes redirectAttributes = new RedirectAttributesModelMap(); TicketReservationModification ticketReservation = new TicketReservationModification(); ticketReservation.setAmount(1);// ww w . j av a2 s.c o m ticketReservation.setTicketCategoryId(ticketCategoryRepository.findByEventId(event.getId()).stream() .findFirst().map(TicketCategory::getId).orElseThrow(IllegalStateException::new)); reservationForm.setReservation(Collections.singletonList(ticketReservation)); return eventController.reserveTicket(eventName, reservationForm, bindingResult, model, servletWebRequest, redirectAttributes, Locale.ENGLISH); }
From source file:com.doitnext.http.router.RestRouterServletTest.java
private void setUpRequest(Object[] testCase, MockHttpServletRequest request) { String httpMethod = (String) testCase[0]; String pathPrefix = (String) testCase[1]; String pathInfo = (String) testCase[2]; String queryString = (String) testCase[3]; String parts[] = queryString.split("&"); String acceptHeader = (String) testCase[4]; String contentTypeHeader = (String) testCase[5]; request.setServletPath(""); request.setContextPath(pathPrefix);/*ww w.j av a 2s. co m*/ request.setPathInfo(pathInfo); request.setMethod(httpMethod); request.setQueryString(queryString); for (String part : parts) { String pieces[] = part.split("="); if (pieces.length > 1) request.addParameter(pieces[0], pieces[1]); } if (acceptHeader != null) request.addHeader("Accept", acceptHeader); if (contentTypeHeader != null) request.setContentType(contentTypeHeader); HttpMethod mthd = HttpMethod.valueOf(httpMethod); if (mthd == HttpMethod.POST || mthd == HttpMethod.PUT) { } }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
public void testAddRelatedItem() throws Exception { // Create dummy user object final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan"); // authenticate user. final Subject subject = getSubjectFromASuccessfulRequest(); // fix data// www . ja v a2 s. co m final List<Integer> fixedItems = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 2); // relation types final String categoryType = "category"; // request through xml format final GenericItem item = new GenericItem(); item.setId(fixedItems.get(1)); item.addRelatedItem(categoryType, fixedItems.get(0)); // prepare request command final StringBuilder requestString = new StringBuilder(); requestString.append("<" + XmlConstants.ELEMENT_REQUEST + ">"); requestString.append(SerializerFactory.getInstance().serializeObject(SerializerFactory.XML, item)); requestString.append("</" + XmlConstants.ELEMENT_REQUEST + ">"); // create request uri final String requestUri = "/service/add-related-items/id.xml"; final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI(requestUri); request.setMethod(METHOD_POST); request.addParameter("id", requestString.toString()); request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject); final MockHttpServletResponse response = new MockHttpServletResponse(); // execute restful service mRestfulController.handleRequest(request, response); // verify final String responseString = response.getContentAsString(); LOG.debug("Response string - " + responseString); assertFalse("No response found", responseString == null || responseString.length() == 0); assertFalse("Response state false", responseString.indexOf("false") != -1); }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
public void testDeleteRelatedItem() throws Exception { // Create dummy user object final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan"); // authenticate user. final Subject subject = getSubjectFromASuccessfulRequest(); // fix data/* w ww . ja v a 2 s .co m*/ final List<Integer> fixedItems = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 2); // relation types final String categoryType = "category"; // add related items mRepositoryService.addRelatedItem(categoryType, fixedItems.get(0), fixedItems.get(1)); // verify final List<Integer> relatedItems = mRepositoryService.getRelatedItems(fixedItems.get(0), categoryType, 0, Integer.MAX_VALUE); assertTrue("No related item found", relatedItems != null && !relatedItems.isEmpty()); // request through xml format final GenericItem item = new GenericItem(); item.setId(fixedItems.get(0)); item.addRelatedItem(categoryType, fixedItems.get(1)); // prepare request command final StringBuilder requestString = new StringBuilder(); requestString.append("<" + XmlConstants.ELEMENT_REQUEST + ">"); requestString.append(SerializerFactory.getInstance().serializeObject(SerializerFactory.XML, item)); requestString.append("</" + XmlConstants.ELEMENT_REQUEST + ">"); // create request uri final String requestUri = "/service/delete-related-items/id.xml"; final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI(requestUri); request.setMethod(METHOD_POST); request.addParameter("id", requestString.toString()); request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject); final MockHttpServletResponse response = new MockHttpServletResponse(); // execute restful service mRestfulController.handleRequest(request, response); // verify final String responseString = response.getContentAsString(); LOG.debug("Response string - " + responseString); assertFalse("No response found", responseString == null || responseString.length() == 0); assertFalse("Response state false", responseString.indexOf("false") != -1); // verify related items final List<Integer> relatedItems2 = mRepositoryService.getRelatedItems(fixedItems.get(0), categoryType, 0, Integer.MAX_VALUE); assertFalse("Related item found", relatedItems2 != null && !relatedItems2.isEmpty()); }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
/** * Request for storing new object./* w w w .j a v a 2s. co m*/ * @throws Exception */ public void testSaveOperation() throws Exception { // Create dummy user object final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan"); // Create fixture data final List<Integer> createdItemIdList = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 1); // Set dummy user with the deletable list of items createdItemIdList.add(dummyUserId); try { final Subject subject = getSubjectFromASuccessfulRequest(); // build mock request final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/service/save/item.xml"); request.setMethod(METHOD_POST); request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject); request.addParameter("item", fixContent()); // Build mock response final MockHttpServletResponse response = new MockHttpServletResponse(); // send request mRestfulController.handleRequest(request, response); // verify response final String content = response.getContentAsString(); assertFalse("Response Content is empty", content.length() == 0); assertTrue("State is false.", content.indexOf("true") != -1); LOG.debug("Response - " + content); } finally { TestCaseRepositoryHelper.fixRemoveItems(mRepositoryService, createdItemIdList); } }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
/** * Request for updating an exsiting object. * @throws Exception//from w w w .j a v a 2 s . co m */ public void testUpdateOperation() throws Exception { // Create dummy user object final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan"); // Create fixture data final List<Integer> createdItemIdList = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 1); // Set dummy user with the deletable list of items createdItemIdList.add(dummyUserId); try { final Subject subject = getSubjectFromASuccessfulRequest(); // build mock request final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/service/update/item.xml"); request.setMethod(METHOD_POST); request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject); request.addParameter("item", fixUpdateRequest(createdItemIdList.get(0))); // Build mock response final MockHttpServletResponse response = new MockHttpServletResponse(); // send request mRestfulController.handleRequest(request, response); // verify response final String content = response.getContentAsString(); assertFalse("Response Content is empty", content.length() == 0); LOG.debug("Response - " + content); assertTrue("Response state false.", content.indexOf("false") == -1); // verify updated object final GenericItem item = mRepositoryService.getItem(createdItemIdList.get(0), GenericItem.class); LOG.debug("Updated item - " + item); assertEquals("New title doesn't match", "hasan-bang", item.getTitle()); } finally { TestCaseRepositoryHelper.fixRemoveAllItems(mRepositoryService); } }
From source file:nl.surfnet.coin.selfservice.interceptor.AuthorityScopeInterceptorTest.java
@Test public void token_session_does_not_equal_request_param_token() throws Exception { ModelAndView modelAndView = buildSecurityContext(ROLE_DASHBOARD_ADMIN); MockHttpServletRequest request = new MockHttpServletRequest(); interceptor.postHandle(request, null, null, modelAndView); // first check if the token is generated and stored in session and modelMap String token = (String) modelAndView.getModelMap().get(TOKEN_CHECK); assertNotNull(token);/*from w w w. ja v a 2s. c om*/ String sessionToken = (String) request.getSession(false).getAttribute(TOKEN_CHECK); assertNotNull(token); assertEquals(token, sessionToken); // now check if the prehandle checks the token if the method is a POST request = new MockHttpServletRequest(); request.setMethod(RequestMethod.POST.name()); try { interceptor.preHandle(request, null, null); fail("Expected security exception"); } catch (Exception e) { } // now check if the prehandle checks the token if the method is a POST request = new MockHttpServletRequest(); request.addParameter(TOKEN_CHECK, sessionToken); request.getSession().setAttribute(TOKEN_CHECK, sessionToken); request.setMethod(RequestMethod.POST.name()); assertTrue(interceptor.preHandle(request, null, null)); }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
/** * Test get request for retrieving an item. * @throws Exception/* w w w. j av a 2 s.com*/ */ public void testGetOperation() throws Exception { final Integer userId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan"); final List<Integer> parentItemIds = new ArrayList<Integer>(); parentItemIds.add(userId); final List<Integer> itemIds = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 10, "blog", parentItemIds); // Execute successful login request. final Subject subject = getSubjectFromASuccessfulRequest(); // Create a new servlet request. final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/service/get/" + itemIds.get(0) + ".xml"); request.setMethod(METHOD_GET); // set parameters request.addParameter(WebConstants.PARAM_LOAD_RELATED_ITEMS, "true"); request.addParameter(WebConstants.PARAM_RELATION_TYPES, "blog, user"); request.addParameter(WebConstants.PARAM_MAX, "1"); // set session id final MockHttpSession session = new MockHttpSession(); session.setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject); request.setSession(session); final MockHttpServletResponse response = new MockHttpServletResponse(); // Execute controller final ModelAndView modelAndView = mRestfulController.handleRequest(request, response); // Verify response assertNull("Model and view is ignored.", modelAndView); LOG.debug("Response - " + response.getContentAsString()); final boolean stateTrue = response.getContentAsString().indexOf("false") == -1; assertTrue("This action should not return false", stateTrue); assertEquals("Response status is not 200.", RESTfulControllerImpl.STATUS_OK_200, response.getStatus()); }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
public void testDeleteOperation() throws Exception { final List<Integer> createdItems = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 1); // create new user object final Integer userId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan"); createdItems.add(userId);//from ww w . j a v a 2 s . c o m try { final Subject subject = getSubjectFromASuccessfulRequest(); final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/service/delete/" + createdItems.get(0) + ".xml"); request.setMethod(METHOD_DELETE); request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject); final MockHttpServletResponse response = new MockHttpServletResponse(); // Execute command mRestfulController.handleRequest(request, response); // Verify impacts final String content = response.getContentAsString(); assertTrue("No response request generated.", content.length() > 0); final boolean stateTrue = content.indexOf("true") != -1; assertTrue("No response state found", stateTrue); assertEquals("Return status 202", RESTfulControllerImpl.STATUS_ACCEPTED_202, 202); LOG.debug("Content - " + content); } finally { TestCaseRepositoryHelper.fixRemoveAllItems(mRepositoryService); } }