org.springframework.test.web.servlet.MvcResult Java Examples
The following examples show how to use
org.springframework.test.web.servlet.MvcResult.
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: KisiControllerTest.java From spring-examples with GNU General Public License v3.0 | 6 votes |
@Test void whenCallTumunuListele_thenReturns200() throws Exception { // given KisiDto kisi = KisiDto.builder().adi("taner").soyadi("temel").build(); when(kisiService.getAll()).thenReturn(Arrays.asList(kisi)); // when MvcResult mvcResult = mockMvc.perform(get("/kisi") .accept(CONTENT_TYPE)).andReturn(); // then String responseBody = mvcResult.getResponse().getContentAsString(); verify(kisiService, times(1)).getAll(); assertThat(objectMapper.writeValueAsString(Arrays.asList(kisi))) .isEqualToIgnoringWhitespace(responseBody); }
Example #2
Source File: TestIMSController.java From blue-marlin with Apache License 2.0 | 6 votes |
@Test public void chart() throws Exception { IMSRequestQuery payload = new IMSRequestQuery(); TargetingChannel tc = new TargetingChannel(); tc.setG(Arrays.asList("g_f")); tc.setA(Arrays.asList("3")); payload.setTargetingChannel(tc); when(invEstSrv.getInventoryDateEstimate(payload.getTargetingChannel())) .thenReturn(new DayImpression()); String reqJson = "{\"targetingChannel\": {\"g\":[\"g_f\"],\"a\":[\"3\"]},\"price\":100}"; MvcResult res = (MvcResult) mockMvc.perform(post("/api/chart").contentType( MediaType.APPLICATION_JSON).content(reqJson)) .andReturn(); System.out.println("chart " + res.toString()); }
Example #3
Source File: ServiceInstanceBindingControllerIntegrationTest.java From spring-cloud-open-service-broker with Apache License 2.0 | 6 votes |
@Test void deleteBindingWithoutAsyncAndHeadersOperationInProgress() throws Exception { setupCatalogService(); setupServiceInstanceBindingService(new ServiceBrokerDeleteOperationInProgressException("task_10")); MvcResult mvcResult = mockMvc.perform(delete(buildDeleteUrl(PLATFORM_INSTANCE_ID, false)) .header(API_INFO_LOCATION_HEADER, API_INFO_LOCATION) .header(ORIGINATING_IDENTITY_HEADER, buildOriginatingIdentityHeader()) .contentType(MediaType.APPLICATION_JSON)) .andExpect(request().asyncStarted()) .andExpect(status().isOk()) .andReturn(); mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isAccepted()) .andExpect(jsonPath("$.operation", is("task_10"))); then(serviceInstanceBindingService) .should() .deleteServiceInstanceBinding(any(DeleteServiceInstanceBindingRequest.class)); verifyDeleteBinding(); }
Example #4
Source File: ServiceInstanceControllerIntegrationTest.java From spring-cloud-open-service-broker with Apache License 2.0 | 6 votes |
@Test void updateServiceInstanceFiltersPlansSucceeds() throws Exception { setupCatalogService(); setupServiceInstanceService(UpdateServiceInstanceResponse .builder() .build()); MvcResult mvcResult = mockMvc .perform(patch(buildCreateUpdateUrl()) .content(updateRequestBodyWithPlan) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(request().asyncStarted()) .andReturn(); mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().string("{}")); UpdateServiceInstanceRequest actualRequest = verifyUpdateServiceInstance(); assertThat(actualRequest.isAsyncAccepted()).isEqualTo(false); assertThat(actualRequest.getPlan().getId()).isEqualTo(actualRequest.getPlanId()); assertHeaderValuesNotSet(actualRequest); }
Example #5
Source File: AttributeControllerDocumentation.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void testDeleteByIdOk() throws Exception { InputStream input = new ClassPathResource( "attribute/SQLViewAttribute.json" ).getInputStream(); MockHttpSession session = getSession( "ALL" ); MvcResult postResult = mvc.perform( post( schema.getRelativeApiEndpoint() ) .session( session ) .contentType( TestUtils.APPLICATION_JSON_UTF8 ) .content( ByteStreams.toByteArray( input ) ) ) .andExpect( status().is( createdStatus ) ).andReturn(); String uid = TestUtils.getCreatedUid( postResult.getResponse().getContentAsString() ); mvc.perform( delete( schema.getRelativeApiEndpoint() + "/{id}", uid ).session( session ).accept( MediaType.APPLICATION_JSON ) ) .andExpect( status().is( deleteStatus ) ) .andDo( documentPrettyPrint( schema.getPlural() + "/delete" ) ); }
Example #6
Source File: ServiceInstanceControllerIntegrationTest.java From spring-cloud-open-service-broker with Apache License 2.0 | 6 votes |
@Test void createServiceInstanceWithEmptyPlatformInstanceIdSucceeds() throws Exception { setupCatalogService(); setupServiceInstanceService(CreateServiceInstanceResponse.builder() .async(true) .build()); // force a condition where the platformInstanceId segment is present but empty // e.g. https://test.app.local//v2/service_instances/[guid] String url = "https://test.app.local/" + buildCreateUpdateUrl(); MvcResult mvcResult = mockMvc.perform(put(url) .content(createRequestBody) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(request().asyncStarted()) .andReturn(); mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isAccepted()); CreateServiceInstanceRequest actualRequest = verifyCreateServiceInstance(); assertHeaderValuesNotSet(actualRequest); }
Example #7
Source File: ServiceInstanceBindingControllerIntegrationTest.java From spring-cloud-open-service-broker with Apache License 2.0 | 6 votes |
@Test void lastOperationHasFailedStatus() throws Exception { setupServiceInstanceBindingService(GetLastServiceBindingOperationResponse.builder() .operationState(OperationState.FAILED) .description("not so good") .build()); MvcResult mvcResult = mockMvc.perform(get(buildLastOperationUrl())) .andExpect(request().asyncStarted()) .andExpect(status().isOk()) .andReturn(); mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(jsonPath("$.state", is(OperationState.FAILED.toString()))) .andExpect(jsonPath("$.description", is("not so good"))); }
Example #8
Source File: ConfigControllerTest.java From Mahuta with Apache License 2.0 | 6 votes |
@Test public void createIndexNoConfig() throws Exception { String indexName = mockNeat.strings().size(20).get(); // Create Index mockMvc.perform(post("/config/index/" + indexName)) .andExpect(status().isOk()) .andDo(print()); // Get all Indexes MvcResult response = mockMvc.perform(get("/config/index")) .andExpect(status().isOk()) .andDo(print()) .andReturn(); // Validate GetIndexesResponse result = mapper.readValue(response.getResponse().getContentAsString(), GetIndexesResponse.class); assertTrue(result.getIndexes().stream().filter(i->i.equalsIgnoreCase(indexName)).findAny().isPresent()); }
Example #9
Source File: MgmtTargetResourceTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Test @Description("Verfies that a properties of new targets are validated as in allowed size range.") public void createTargetWithInvalidPropertyBadRequest() throws Exception { final Target test1 = entityFactory.target().create().controllerId("id1") .name(RandomStringUtils.randomAlphanumeric(NamedEntity.NAME_MAX_SIZE + 1)).build(); final MvcResult mvcResult = mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) .content(JsonBuilder.targets(Arrays.asList(test1), true)).contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn(); assertThat(targetManagement.count()).isEqualTo(0); // verify response json exception message final ExceptionInfo exceptionInfo = ResourceUtility .convertException(mvcResult.getResponse().getContentAsString()); assertThat(exceptionInfo.getExceptionClass()).isEqualTo(ConstraintViolationException.class.getName()); assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_REPO_CONSTRAINT_VIOLATION.getKey()); }
Example #10
Source File: SpringBootJpaRestTest.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
@Test public void shouldUpdateEntity() throws Exception { User user = new User("张三", "123456", "[email protected]"); User user2 = new User("李四", "123456", "[email protected]"); MvcResult mvcResult = mockMvc.perform(post("/user").content(objectMapper.writeValueAsString(user))) .andExpect(status().isCreated()).andReturn(); String location = mvcResult.getResponse().getHeader("Location"); assertThat(location).isNotNull(); mockMvc.perform(put(location).content(objectMapper.writeValueAsString(user2))) .andExpect(status().isNoContent()); mockMvc.perform(get(location)).andExpect(status().isOk()).andExpect(jsonPath("$.username").value("李四")) .andExpect(jsonPath("$.password").value("123456")); }
Example #11
Source File: AttributeControllerDocumentation.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void testUpdate() throws Exception { InputStream input = new ClassPathResource( "attribute/SQLViewAttribute.json" ).getInputStream(); MockHttpSession session = getSession( "ALL" ); MvcResult postResult = mvc.perform( post( schema.getRelativeApiEndpoint() ) .session( session ) .contentType( TestUtils.APPLICATION_JSON_UTF8 ) .content( ByteStreams.toByteArray( input ) ) ) .andExpect( status().is( createdStatus ) ).andReturn(); String uid = TestUtils.getCreatedUid( postResult.getResponse().getContentAsString() ); InputStream inputUpdate = new ClassPathResource( "attribute/SQLViewAttribute.json" ).getInputStream(); mvc.perform( put( schema.getRelativeApiEndpoint() + "/" + uid ) .session( session ) .contentType( TestUtils.APPLICATION_JSON_UTF8 ) .content( ByteStreams.toByteArray( inputUpdate ) ) ) .andExpect( status().is( updateStatus ) ) .andDo( documentPrettyPrint( schema.getPlural() + "/update" ) ); }
Example #12
Source File: MockMvcApplicationTest.java From angularjs-springmvc-sample-boot with Apache License 2.0 | 6 votes |
@Test public void createSpringfoxSwaggerJson() throws Exception { //String designFirstSwaggerLocation = Swagger2MarkupTest.class.getResource("/swagger.yaml").getPath(); MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs") .accept(MediaType.APPLICATION_JSON)) .andDo( SwaggerResultHandler.outputDirectory(outputDir) .build() ) .andExpect(status().isOk()) .andReturn(); //String springfoxSwaggerJson = mvcResult.getResponse().getContentAsString(); //SwaggerAssertions.assertThat(Swagger20Parser.parse(springfoxSwaggerJson)).isEqualTo(designFirstSwaggerLocation); }
Example #13
Source File: ApplicationMockMvcTest.java From spring-microservice-sample with GNU General Public License v3.0 | 6 votes |
@Test public void createPostWithoutAuthentication() throws Exception { Post _data = Post.builder().title("my first post").content("my content of my post").build(); given(this.postService.createPost(any(PostForm.class))) .willReturn(_data); MvcResult result = this.mockMvc .perform( post("/posts") .content(objectMapper.writeValueAsString(PostForm.builder().title("my first post").content("my content of my post").build())) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isUnauthorized()) .andReturn(); log.debug("mvc result::" + result.getResponse().getContentAsString()); verify(this.postService, times(0)).createPost(any(PostForm.class)); verifyNoMoreInteractions(this.postService); }
Example #14
Source File: TestService.java From exchange-gateway-rest with Apache License 2.0 | 6 votes |
public RestApiOrderBook getOrderBook(String symbol) throws Exception { String url = SYNC_TRADE_API_V1 + String.format("/symbols/%s/orderbook", symbol); MvcResult result = mockMvc.perform(get(url).param("depth", "-1")) .andExpect(status().isOk()) .andExpect(content().contentType(applicationJson)) .andExpect(jsonPath("$.data.symbol", is(symbol))) .andExpect(jsonPath("$.gatewayResultCode", is(0))) .andExpect(jsonPath("$.coreResultCode", is(100))) .andReturn(); String contentAsString = result.getResponse().getContentAsString(); log.debug("contentAsString=" + contentAsString); TypeReference<RestGenericResponse<RestApiOrderBook>> typeReference = new TypeReference<RestGenericResponse<RestApiOrderBook>>() { }; RestGenericResponse<RestApiOrderBook> response = objectMapper.readValue(contentAsString, typeReference); return response.getData(); }
Example #15
Source File: SharedHttpSessionTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void noHttpSession() throws Exception { MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new TestController()) .apply(sharedHttpSession()) .build(); String url = "/no-session"; MvcResult result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); HttpSession session = result.getRequest().getSession(false); assertNull(session); result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); session = result.getRequest().getSession(false); assertNull(session); url = "/session"; result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); session = result.getRequest().getSession(false); assertNotNull(session); assertEquals(1, session.getAttribute("counter")); }
Example #16
Source File: ServiceInstanceBindingControllerIntegrationTest.java From spring-cloud-open-service-broker with Apache License 2.0 | 6 votes |
@Test void getBindingToAppSucceeds() throws Exception { setupServiceInstanceBindingService(GetServiceInstanceAppBindingResponse.builder() .build()); MvcResult mvcResult = mockMvc.perform(get(buildCreateUrl(PLATFORM_INSTANCE_ID, false)) .header(API_INFO_LOCATION_HEADER, API_INFO_LOCATION) .header(ORIGINATING_IDENTITY_HEADER, buildOriginatingIdentityHeader()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)) .andExpect(request().asyncStarted()) .andReturn(); mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()); GetServiceInstanceBindingRequest actualRequest = verifyGetBinding(); assertHeaderValuesSet(actualRequest); }
Example #17
Source File: BookResourceTest.java From spring-react-boilerplate with MIT License | 6 votes |
@Test public void addNewBooksRestTest() throws Exception { Book book = new Book(); book.setId(2L); book.setName("New Test Book"); book.setPrice(1.75); String json = mapper.writeValueAsString(book); MvcResult result = mockMvc.perform(post("/api/addbook") .contentType(MediaType.APPLICATION_JSON) .content(json) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andReturn(); String expected = "[{'id':1,'name':'Spring Boot React Example','price':0.0}," + "{'id':2,'name':'New Test Book','price':1.75}]"; JSONAssert.assertEquals(expected,result.getResponse().getContentAsString(), false); }
Example #18
Source File: FileTestUtils.java From full-teaching with Apache License 2.0 | 6 votes |
public static FileGroup uploadTestFile(MockMvc mvc, HttpSession httpSession, FileGroup fg, Course c, MockMultipartFile file) { try { MvcResult result = mvc.perform(MockMvcRequestBuilders.fileUpload(upload_uri.replace("{courseId}",""+c.getId())+fg.getId()) .file(file) .session((MockHttpSession) httpSession) ).andReturn(); String content = result.getResponse().getContentAsString(); System.out.println(content); return json2FileGroup(content); } catch (Exception e) { e.printStackTrace(); fail("EXCEPTION: //FileTestUtils.uploadTestFile ::"+e.getClass().getName()); } return null; }
Example #19
Source File: ServiceInstanceControllerIntegrationTest.java From spring-cloud-open-service-broker with Apache License 2.0 | 6 votes |
@Test void createServiceInstanceWithAsyncAndHeadersOperationInProgress() throws Exception { setupCatalogService(); setupServiceInstanceService(new ServiceBrokerCreateOperationInProgressException("task_10")); MvcResult mvcResult = mockMvc.perform(put(buildCreateUpdateUrl(PLATFORM_INSTANCE_ID, true)) .content(createRequestBody) .contentType(MediaType.APPLICATION_JSON) .header(API_INFO_LOCATION_HEADER, API_INFO_LOCATION) .header(ORIGINATING_IDENTITY_HEADER, buildOriginatingIdentityHeader()) .accept(MediaType.APPLICATION_JSON)) .andExpect(request().asyncStarted()) .andExpect(status().isOk()) .andReturn(); mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isAccepted()) .andExpect(jsonPath("$.operation", is("task_10"))); CreateServiceInstanceRequest actualRequest = verifyCreateServiceInstance(); assertThat(actualRequest.isAsyncAccepted()).isEqualTo(true); assertHeaderValuesSet(actualRequest); }
Example #20
Source File: ConsumerDemoApplicationTests.java From lion with Apache License 2.0 | 5 votes |
@Test public void mockTestBlockChainDecrypt() throws Exception { String blockHash = "a0395b258720152e33155253297b182e"; MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.post("/blockchain/decrypt/" + blockHash) .accept(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); System.out.println(mvcResult); }
Example #21
Source File: StatusResultMatchersTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void statusRanges() throws Exception { for (HttpStatus status : HttpStatus.values()) { MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(status.value()); MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response); switch (status.series().value()) { case 1: this.matchers.is1xxInformational().match(mvcResult); break; case 2: this.matchers.is2xxSuccessful().match(mvcResult); break; case 3: this.matchers.is3xxRedirection().match(mvcResult); break; case 4: this.matchers.is4xxClientError().match(mvcResult); break; case 5: this.matchers.is5xxServerError().match(mvcResult); break; default: fail("Unexpected range for status code value " + status); } } }
Example #22
Source File: AbstractSpringDocTest.java From springdoc-openapi with Apache License 2.0 | 5 votes |
@Test public void testApp() throws Exception { className = getClass().getSimpleName(); String testNumber = className.replaceAll("[^0-9]", ""); MvcResult mockMvcResult = mockMvc.perform(get(Constants.DEFAULT_API_DOCS_URL)).andExpect(status().isOk()) .andExpect(jsonPath("$.openapi", is("3.0.1"))).andReturn(); String result = mockMvcResult.getResponse().getContentAsString(); String expected = getContent("results/app" + testNumber + ".json"); assertEquals(expected, result, true); }
Example #23
Source File: ConfirmResetControllerTest.java From staffjoy with MIT License | 5 votes |
@Test public void testGetConfirmResetWrongToken() throws Exception { String userId = UUID.randomUUID().toString(); String email = "[email protected]"; String signingToken = appProps.getSigningSecret(); String token = Sign.generateEmailConfirmationToken(userId, email, signingToken); token += "wrong_token"; // get request MvcResult mvcResult = mockMvc.perform(get("/reset/" + token)) .andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:" + ResetController.PASSWORD_RESET_PATH)) .andReturn(); }
Example #24
Source File: PrintingResultHandler.java From spring4-understanding with Apache License 2.0 | 5 votes |
protected void printAsyncResult(MvcResult result) throws Exception { HttpServletRequest request = result.getRequest(); this.printer.printValue("Async started", request.isAsyncStarted()); Object asyncResult = null; try { asyncResult = result.getAsyncResult(0); } catch (IllegalStateException ex) { // Not set } this.printer.printValue("Async result", asyncResult); }
Example #25
Source File: MvcIntegrationTestUtils.java From find with MIT License | 5 votes |
public String[] getFields(final MockMvc mockMvc, final String subPath, final String... fieldTypes) throws Exception { final MockHttpServletRequestBuilder requestBuilder = get(FieldsController.FIELDS_PATH + subPath) .with(authentication(userAuth())); requestBuilder.param(FieldsController.FIELD_TYPES_PARAM, fieldTypes); addFieldRequestParams(requestBuilder); final MvcResult mvcResult = mockMvc.perform(requestBuilder) .andReturn(); final Collection<Map<String, String>> tagNames = JsonPath.compile("$").read(mvcResult.getResponse().getContentAsString()); return tagNames.stream().map(tagName -> tagName.get("id")).toArray(String[]::new); }
Example #26
Source File: ConsumerDemoApplicationTests.java From lion with Apache License 2.0 | 5 votes |
@Test public void mockTestInit() throws Exception { MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.get("/init") .accept(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); System.out.println(mvcResult); }
Example #27
Source File: TopicHistoricalTest.java From WeEvent with Apache License 2.0 | 5 votes |
@Test public void testEventList() throws Exception { String content = "{\"groupId\":\"1\",\"userId\":\"1\",\"brokerId\":\"" + this.brokerIdMap.get("brokerId") + "\",\"beginDate\":\"2019-12-08\",\"endDate\":\"2099-12-15\"}"; MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/historicalData/eventList") .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); GovernanceResult governanceResult = JsonHelper.json2Object(result, GovernanceResult.class); Assert.assertEquals(governanceResult.getStatus().toString(), "200"); }
Example #28
Source File: IndexControllerTest.java From SMSC with Apache License 2.0 | 5 votes |
@Test public void testAdminActionWithoutFilePathWithMockedResourceModified() throws Exception { given(this.staticResourceService.getResource("classpath:META-INF/resources/io.smsc.admin/index.html")).willReturn(new ClassPathResource("index.html")); MvcResult result = mockMvc .perform(get("/admin")) .andReturn(); assertThat(result.getResponse().getStatus()).isEqualTo(200); assertThat(result.getResponse().getContentAsString()).contains("SMSC"); }
Example #29
Source File: LoginControllerTest.java From staffjoy with MIT License | 5 votes |
@Test public void testGet() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/login")) .andExpect(status().isOk()) .andExpect(view().name(Constant.VIEW_LOGIN)) .andExpect(content().string(containsString(pageFactory.buildLoginPage().getDescription()))) .andReturn(); log.info(mvcResult.getResponse().getContentAsString()); }
Example #30
Source File: LoginControllerTest.java From staffjoy with MIT License | 5 votes |
@Test public void testAleadyLoggedIn() throws Exception { MvcResult mvcResult = mockMvc.perform(post("/login") .header(AuthConstant.AUTHORIZATION_HEADER, AuthConstant.AUTHORIZATION_AUTHENTICATED_USER)) .andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:" + HelperService.buildUrl("http", "myaccount." + envConfig.getExternalApex()))) .andReturn(); }