@Test public void testRegisterActivity() throws Exception { String userId = "412bac09-b9a0-46b5-a283-7442fa1eb76c"; String token = "3f1d9898-5531-4753-80fa-2e164c5ba754"; MvcResult result = mockMvc .perform( MockMvcRequestBuilders.post( "/activity/register?userId=" + userId + "&token=" + token) .param("type", "旅行") .param("introduction", "DD活动期间晴空万里,道路通畅") .param("cover", "4d51a321-f953-4623-b7ab-abd4fb858e77") .param("cover", "59336875-0128-4121-862a-22d1db86fe03") .param("location", "南京邮电大学") .param("longitude", "118.869529") .param("latitude", "32.02632") .param("start", "1436494940937") .param("end", "1436494955800") .param("province", "江苏省") .param("city", "南京") .param("district", "鼓楼区") .param("pay", "我请客") .param("seat", "2")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().encoding("UTF-8")) .andExpect( MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) .andExpect(MockMvcResultMatchers.jsonPath("$.result").value(0)) .andDo(MockMvcResultHandlers.print()) .andReturn(); Assert.assertNull(result.getModelAndView()); }
@Test public void testFilters() throws Exception { int index = 1; for (String json : jsonList) { MvcResult result = ControllerUtil.performRouterRequest(this.mockMvc, json); List<ExtDirectResponse> responses = ControllerUtil.readDirectResponses(result.getResponse().getContentAsByteArray()); assertThat(responses).hasSize(1); ExtDirectResponse resp = responses.get(0); assertThat(resp.getAction()).isEqualTo("remoteProviderStoreRead"); assertThat(resp.getMethod()).isEqualTo("methodFilter"); assertThat(resp.getType()).isEqualTo("rpc"); assertThat(resp.getTid()).isEqualTo(index); assertThat(resp.getMessage()).isNull(); assertThat(resp.getWhere()).isNull(); assertThat(resp.getResult()).isNotNull(); List<Row> rows = ControllerUtil.convertValue( resp.getResult(), new TypeReference<List<Row>>() { // nothing here }); assertThat(rows).hasSize(1); assertThat(rows.get(0).getId()).isEqualTo(index); index++; } assertThat(index).isEqualTo(34); }
@Test public void correctlyRecordsMetricsForFailedDeferredResultResponse() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, MetricFilterAutoConfiguration.class); MetricsFilter filter = context.getBean(MetricsFilter.class); CountDownLatch latch = new CountDownLatch(1); MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController(latch)) .addFilter(filter) .build(); String attributeName = MetricsFilter.class.getName() + ".StopWatch"; MvcResult result = mvc.perform(post("/createFailure")) .andExpect(status().isOk()) .andExpect(request().asyncStarted()) .andExpect(request().attribute(attributeName, is(notNullValue()))) .andReturn(); latch.countDown(); try { mvc.perform(asyncDispatch(result)); fail(); } catch (Exception ex) { assertThat(result.getRequest().getAttribute(attributeName)).isNull(); verify(context.getBean(CounterService.class)).increment("status.500.createFailure"); } finally { context.close(); } }
// Test POST or PUT on /restAPI/items, to add a document private void testAddOneNewDoc(boolean isPost) throws Exception { ModelMap newDoc = createDoc("Bach", "unknonwn", "Wonderful"); String jsonNewDoc = objectToJson(newDoc); MockHttpServletRequestBuilder builder; if (isPost) builder = post("/restAPI/items/"); else builder = put("/restAPI/items"); MvcResult result = mockMvc .perform(builder.contentType(contentType).content(jsonNewDoc)) .andExpect(status().isCreated()) .andReturn(); // Get the response body String resultJson = result.getResponse().getContentAsString(); // Get the document ID returned DocIDReturn idRet = mapper.readValue(resultJson, DocIDReturn.class); // Now in the database there shall be 3 documents assertEquals(3, docRepository.count()); // Get the document just added, and verify StoredDocument retrievedDoc = docRepository.findOne(idRet.getId()); assertEquals(newDoc, retrievedDoc.getDocument()); }
private ActionDoc callApi(String method) throws Exception { ApiRequestParams params = ApiRequestParams.builder() .apiNs("Ext.ns") .actionNs("actionns") .group("doc") .configuration(configurationService.getConfiguration()) .build(); MockHttpServletRequestBuilder request = get("/api-debug-doc.js").accept(MediaType.ALL).characterEncoding("UTF-8"); request.param("apiNs", params.getApiNs()); request.param("actionNs", params.getActionNs()); request.param("group", params.getGroup()); MvcResult result = mockMvc .perform(request) .andExpect(status().isOk()) .andExpect(content().contentType("application/javascript")) .andReturn(); ApiControllerTest.compare(result, ApiControllerTest.groupApisWithDoc("actionns"), params); ActionDoc doc = getCommentForMethod(result.getResponse().getContentAsString(), method); return doc; }
@Test public void testCreateCustomer() throws Exception { long now = System.currentTimeMillis(); String f = "Joe", l = "Doe"; String jsonOfJoeDoe = "{ \"signupDate\":" + now + ",\"firstName\":\"" + f + "\",\"lastName\":\"" + l + "\"}"; MvcResult mvcResult = mockMvc .perform( post("/users/{userId}/customers", userId) .accept(applicationJsonMediaType) .content(jsonOfJoeDoe) .contentType(this.applicationJsonMediaType)) .andExpect(status().isCreated()) .andExpect(content().contentType(this.applicationJsonMediaType)) .andReturn(); mockServer.verify(); String locationUri = mvcResult.getResponse().getHeader("Location"); Assert.assertTrue(locationUri.contains("/users/" + userId + "/customers/")); }
@Test public void voteAndGetResults() throws Exception { // do 5 votes vote(); MvcResult result = mockMvc .perform( get("/vote/showWinner") .contentType(MediaType.APPLICATION_JSON) .with(httpBasic("user", ""))) .andExpect(status().isOk()) .andReturn(); String contentAsString = result.getResponse().getContentAsString(); ObjectMapper mapper = new ObjectMapper(); VoteResult[] voteResult = mapper.readValue(new StringReader(contentAsString), VoteResult[].class); // check we have results for all restaurants assertEquals(2, voteResult.length); // check it was sorted properly assertEquals(RESTAURANT_B_NAME, voteResult[0].getRestaurantName()); // check votes counted properly assertEquals(3, voteResult[0].getVotes()); assertEquals(2, voteResult[1].getVotes()); }
@Test public void testVoteNone() { Vote correctVote = new Vote(); correctVote.setRestaurantId(Long.MIN_VALUE); Restaurant restaurant = new Restaurant(); restaurant.setRestaurantId(Long.MIN_VALUE); when(restaurantRepository.findOne(Long.MIN_VALUE)).thenReturn(restaurant); Restaurant votingRestaurant = new Restaurant(); votingRestaurant.setRestaurantId(Long.MIN_VALUE); Voting identicalVoting = new Voting(); identicalVoting.setRestaurant(votingRestaurant); when(votingRepository.findByUser("admin")).thenReturn(identicalVoting); try { MvcResult outdatedVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(correctVote))) .andExpect(status().isOk()) .andReturn(); String outdatedVoteResString = outdatedVoteRes.getResponse().getContentAsString(); assertTrue(outdatedVoteResString.contains(Status.IGNORED.getStatusValue())); } catch (Exception e) { fail(); } }
@Test public void testResetPassword() throws Exception { String username = "******"; User user = userManager.getUserByUsername(username); String token = userManager.generateRecoveryToken(user); String password = "******"; Wiser wiser = startWiser(getSmtpPort()); ResultActions update = mockMvc .perform( post("/updatePassword") .param("username", username) .param("token", token) .param("password", password)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/")); wiser.stop(); assertTrue(wiser.getMessages().size() == 1); MvcResult result = update.andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(); assertNotNull(session.getAttribute(BaseFormController.MESSAGES_KEY)); assertNull(session.getAttribute(BaseFormController.ERRORS_MESSAGES_KEY)); }
@Test public void testGetText() throws Exception { String inputString = "User related info!"; FormData data = new FormData(); data.setComment(inputString); mockMvc = MockMvcBuilders.standaloneSetup(new ActionController()).build(); MvcResult result = this.mockMvc .perform(get("/users").contentType(MediaType.APPLICATION_JSON).content(data.toString())) .andExpect(status().isOk()) .andReturn(); String returnString = result.getResponse().getContentAsString(); ObjectMapper objectMapper = new ObjectMapper(); logger.info("Call to /users returned: " + returnString); // convert json string to object FormActionResult returnData = objectMapper.readValue(returnString.getBytes(), FormActionResult.class); String expectedString = returnData.getFormData().getComment(); logger.debug("USERS ACTION RETURNED: " + expectedString); assertTrue( "Expected data: \"" + inputString + "\" actual data=\"" + expectedString + "\" ", inputString.equals(expectedString)); }
@Test public void shouldGetPageWithEmailError() throws Exception { // when MvcResult mvcResult = mockMvc .perform( post("/register") .secure(true) .session(session) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("name", expectedUser.getName()) .param("email", "incorrect_email") .param( (csrfToken != null ? csrfToken.getParameterName() : "_csrf"), (csrfToken != null ? csrfToken.getToken() : ""))) // then .andExpect(status().isOk()) .andExpect(content().contentType("text/html;charset=UTF-8")) .andReturn(); RegistrationPage registrationPage = new RegistrationPage(mvcResult.getResponse().getContentAsString()); registrationPage.hasErrors("user", "Please provide a valid email"); registrationPage.hasRegistrationFields(expectedUser.getName(), "incorrect_email"); }
private void doRequestWithoutDocs(String url) throws Exception { ApiRequestParams params = ApiRequestParams.builder() .apiNs("Ext.ns") .actionNs("actionns") .group("doc") .configuration(configurationService.getConfiguration()) .build(); MockHttpServletRequestBuilder request = get(url).accept(MediaType.ALL).characterEncoding("UTF-8"); request.param("apiNs", params.getApiNs()); request.param("actionNs", params.getActionNs()); request.param("group", params.getGroup()); MvcResult result = mockMvc .perform(request) .andExpect(status().isOk()) .andExpect(content().contentType("application/javascript")) .andReturn(); ApiControllerTest.compare(result, ApiControllerTest.groupApisWithDoc("actionns"), params); Assert.doesNotContain( "/**", result.getResponse().getContentAsString(), "generation of api.js should not contain method documentation"); }
@Test public void shouldGetPageWithEmailAlreadyTakenError() throws Exception { // given userDAO.save( new User("already_exists_id", "test name", "*****@*****.**", "Password123")); // when MvcResult mvcResult = mockMvc .perform( post("/register") .secure(true) .session(session) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("name", expectedUser.getName()) .param("email", "*****@*****.**") .param( (csrfToken != null ? csrfToken.getParameterName() : "_csrf"), (csrfToken != null ? csrfToken.getToken() : ""))) // then .andExpect(status().isOk()) .andExpect(content().contentType("text/html;charset=UTF-8")) .andReturn(); RegistrationPage registrationPage = new RegistrationPage(mvcResult.getResponse().getContentAsString()); registrationPage.hasErrors("user", "That email address has already been taken"); registrationPage.hasRegistrationFields(expectedUser.getName(), "*****@*****.**"); }
@Test public void hidesStsMilestoneDownloadsIfNotAvailable() throws Exception { String responseXml = Fixtures.load("/fixtures/tools/sts_downloads_without_milestones.xml"); stub(restTemplate.getForObject(anyString(), eq(String.class))).toReturn(responseXml); MvcResult mvcResult = mockMvc .perform(get("/tools/sts/all")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith("text/html")) .andReturn(); Document document = Jsoup.parse(mvcResult.getResponse().getContentAsString()); assertThat( document.select(".milestone--release h2.tool-versions--version").text(), not(allOf(containsString("STS"), containsString(".M")))); assertThat( document.select(".milestone--release .item--dropdown a").attr("href"), not( allOf( containsString("http://download.springsource.com/milestone/STS/"), containsString("spring-tool-suite"), containsString("win32-installer.exe")))); }
@Test public void listUsers_in_anotherZone() throws Exception { String subdomain = generator.generate(); MockMvcUtils.IdentityZoneCreationResult result = utils() .createOtherIdentityZoneAndReturnResult( subdomain, getMockMvc(), getWebApplicationContext(), null); String zoneAdminToken = result.getZoneAdminToken(); createUser( getScimUser(), zoneAdminToken, IdentityZone.getUaa().getSubdomain(), result.getIdentityZone().getId()); MockHttpServletRequestBuilder get = MockMvcRequestBuilders.get("/Users") .header("X-Identity-Zone-Subdomain", subdomain) .header("Authorization", "Bearer " + zoneAdminToken) .accept(APPLICATION_JSON); MvcResult mvcResult = getMockMvc().perform(get).andExpect(status().isOk()).andReturn(); SearchResults searchResults = JsonUtils.readValue(mvcResult.getResponse().getContentAsString(), SearchResults.class); MatcherAssert.assertThat(searchResults.getResources().size(), is(1)); }
@Test public void verification_link() throws Exception { ScimUser joel = setUpScimUser(); MockHttpServletRequestBuilder get = setUpVerificationLinkRequest(joel, scimCreateToken); MvcResult result = getMockMvc().perform(get).andExpect(status().isOk()).andReturn(); VerificationResponse verificationResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), VerificationResponse.class); assertThat( verificationResponse.getVerifyLink().toString(), startsWith("http://localhost/verify_user")); String query = verificationResponse.getVerifyLink().getQuery(); String code = getQueryStringParam(query, "code"); assertThat(code, is(notNullValue())); ExpiringCode expiringCode = codeStore.retrieveCode(code); assertThat(expiringCode.getExpiresAt().getTime(), is(greaterThan(System.currentTimeMillis()))); assertThat(expiringCode.getIntent(), is(REGISTRATION.name())); Map<String, String> data = JsonUtils.readValue(expiringCode.getData(), new TypeReference<Map<String, String>>() {}); assertThat(data.get(InvitationConstants.USER_ID), is(notNullValue())); assertThat(data.get(CLIENT_ID), is(clientDetails.getClientId())); assertThat(data.get(REDIRECT_URI), is(HTTP_REDIRECT_EXAMPLE_COM)); }
@Override public void handle(MvcResult result) throws Exception { @SuppressWarnings("unchecked") Map<String, Object> configuration = (Map<String, Object>) result.getRequest().getAttribute(ATTRIBUTE_NAME_CONFIGURATION); this.delegate.handle(result.getRequest(), result.getResponse(), configuration); }
@Test public void browser() throws Exception { MvcResult response = this.mockMvc .perform(get("/actuator/").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()) .andReturn(); assertEquals("/actuator/browser.html", response.getResponse().getForwardedUrl()); }
@Test public void shouldGetFriends() throws Exception { MvcResult result = mockMvc .perform(get("/user/" + FRIEND_USERNAME + "/friend/")) .andExpect(status().isOk()) .andReturn(); String parsedFriends = mapper.writeValueAsString(friendService.getFriends(FRIEND_USERNAME)); assertEquals(parsedFriends, result.getResponse().getContentAsString()); }
@Test public void testVoteSuccess() { Vote correctVote = new Vote(); correctVote.setRestaurantId(Long.MIN_VALUE); Restaurant restaurant = new Restaurant(); restaurant.setRestaurantId(Long.MIN_VALUE); when(restaurantRepository.findOne(Long.MIN_VALUE)).thenReturn(restaurant); when(votingRepository.findByUser("admin")).thenReturn(null); try { MvcResult successVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(correctVote))) .andExpect(status().isOk()) .andReturn(); String outdatedVoteResString = successVoteRes.getResponse().getContentAsString(); assertTrue(outdatedVoteResString.contains(Status.SUCCESS.getStatusValue())); } catch (Exception e) { fail(); } LocalTime currentTime = LocalTime.now(); if (currentTime.isBefore(RestaurantController.DEADLINE)) { Restaurant votingRestaurant = new Restaurant(); votingRestaurant.setRestaurantId(Long.MAX_VALUE); Voting identicalVoting = new Voting(); identicalVoting.setRestaurant(votingRestaurant); when(votingRepository.findByUser("admin")).thenReturn(identicalVoting); try { MvcResult actualVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(correctVote))) .andExpect(status().isOk()) .andReturn(); String outdatedVoteResString = actualVoteRes.getResponse().getContentAsString(); assertTrue(outdatedVoteResString.contains(Status.SUCCESS.getStatusValue())); } catch (Exception e) { fail(); } } }
@Test public void noticeList() throws Exception { MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/admin/skc/notice/list")).andReturn(); List<NoticeVO> list = (List<NoticeVO>) result.getModelAndView().getModel().get("list"); for (NoticeVO noticeVO : list) { logger.info(noticeVO.toString()); } }
@Test public void testView() throws Exception { MvcResult result = mockMvc .perform(MockMvcRequestBuilders.get("/user/1")) .andExpect(MockMvcResultMatchers.view().name("user/view")) .andExpect(MockMvcResultMatchers.model().attributeExists("user")) .andDo(MockMvcResultHandlers.print()) .andReturn(); Assert.assertNotNull(result.getModelAndView().getModel().get("user")); }
@Test public void testZip2() throws Exception { MvcResult mvcResult = mockMvc .perform(post("/").param("addr", "花蓮縣鳳林鎮信義路249號")) .andExpect(request().asyncStarted()) .andExpect(request().asyncStarted()) .andExpect(request().asyncResult(is(not(isEmptyOrNullString())))) .andReturn(); List<Post5> zips = (List<Post5>) mvcResult.getRequest().getAttribute("zips"); assertThat("Error zip.", zips, is(hasSize(2))); }
@Test public void noticeDelete() throws Exception { MvcResult result = mockMvc .perform(MockMvcRequestBuilders.get("/admin/skc/notice/delete").param("no_seq", "6")) .andReturn(); NoticeVO noticeVO = (NoticeVO) result.getModelAndView().getModel().get("noticeVO"); logger.info(noticeVO.toString()); }
// Test the get users command from controller (primarily to check JSON parsers) @Test public void testGetUsers() throws Exception { String url = "/user/info"; MvcResult result = mvc.perform(MockMvcRequestBuilders.get(url).accept(MediaType.APPLICATION_JSON)).andReturn(); String content = result.getResponse().getContentAsString(); int status = result.getResponse().getStatus(); Assert.assertEquals("Expected 200", 200, status); Assert.assertTrue("Expected HTTP body", content.trim().length() > 0); }
@Test public void errorPageAvailableWithMvcIncluded() throws Exception { setup( (ConfigurableWebApplicationContext) SpringApplication.run(WebMvcIncludedConfiguration.class)); MvcResult response = this.mockMvc .perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()) .andReturn(); String content = response.getResponse().getContentAsString(); assertTrue("Wrong content: " + content, content.contains("status=999")); }
@Test(dataProvider = "addrs") public void testZip1(String zipcode, String addr) throws Exception { logger.debug("測試{}:{}", zipcode, addr); MvcResult mvcResult = mockMvc .perform(post("/").param("addr", addr)) .andExpect(request().asyncStarted()) .andExpect(request().asyncStarted()) .andExpect(request().asyncResult(is(not(isEmptyOrNullString())))) .andReturn(); List<Post5> zips = (List<Post5>) mvcResult.getRequest().getAttribute("zips"); assertThat("Error zip.", zips, is(hasSize(1))); assertThat("Error zip.", zips.get(0).getZipcode(), is(equalTo(zipcode))); }
@Test public void testVoteError() { try { Vote wrongVote = new Vote(); wrongVote.setRestaurantId(Long.MAX_VALUE); when(restaurantRepository.findOne(Long.MAX_VALUE)).thenReturn(null); MvcResult wrongIdVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(wrongVote))) .andExpect(status().isOk()) .andReturn(); String wrongIdVoteResponseString = wrongIdVoteRes.getResponse().getContentAsString(); assertTrue(wrongIdVoteResponseString.contains(Status.FAILED.getStatusValue())); assertTrue(wrongIdVoteResponseString.contains(RestaurantController.WRONG_RESTAURANT_MSG)); LocalTime currentTime = LocalTime.now(); if (currentTime.isAfter(RestaurantController.DEADLINE)) { Vote correctVote = new Vote(); correctVote.setRestaurantId(Long.MIN_VALUE); Restaurant restaurant = new Restaurant(); restaurant.setRestaurantId(Long.MIN_VALUE); when(restaurantRepository.findOne(Long.MIN_VALUE)).thenReturn(restaurant); Restaurant votingRestaurant = new Restaurant(); votingRestaurant.setRestaurantId(Long.MAX_VALUE); Voting outdatedVoting = new Voting(); outdatedVoting.setRestaurant(votingRestaurant); when(votingRepository.findByUser("admin")).thenReturn(outdatedVoting); MvcResult outdatedVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(correctVote))) .andExpect(status().isOk()) .andReturn(); String outdatedVoteResString = outdatedVoteRes.getResponse().getContentAsString(); assertTrue(outdatedVoteResString.contains(Status.FAILED.getStatusValue())); } } catch (Exception e) { fail(); } }
@Test public void testShowResetPasswordFormBadToken() throws Exception { String username = "******"; String badtoken = RandomStringUtils.random(32); ResultActions update = mockMvc .perform(get("/updatePassword").param("username", username).param("token", badtoken)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/")); MvcResult result = update.andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(); assertNotNull(session.getAttribute(BaseFormController.ERRORS_MESSAGES_KEY)); }
private MockHttpServletResponse getResponse(String url, Map<String, String> params) throws Exception { MockHttpServletRequestBuilder request = get(url); if (params != null && params.size() > 0) { for (String key : params.keySet()) { request.param(key, params.get(key)); } } ResultActions result = this.mockMvc.perform(request); result.andExpect(MockMvcResultMatchers.status().is(this.HttpStatus)); MvcResult mvcresult = result.andReturn(); MockHttpServletResponse mockresponse = mvcresult.getResponse(); return mockresponse; }