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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
Source File: RequestResultMatchers.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Assert a session attribute value with the given Hamcrest {@link Matcher}. */ public <T> ResultMatcher sessionAttribute(final String name, final Matcher<T> matcher) { return new ResultMatcher() { @Override @SuppressWarnings("unchecked") public void match(MvcResult result) { T value = (T) result.getRequest().getSession().getAttribute(name); assertThat("Session attribute '" + name + "'", value, matcher); } }; }
Example #21
Source File: CallableControllerTests.java From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
@Test public void responseBody() throws Exception { MvcResult mvcResult = this.mockMvc.perform(get("/async/callable/response-body")) .andExpect(request().asyncStarted()).andExpect(request().asyncResult("Callable result")).andReturn(); this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk()) .andExpect(content().contentType("text/plain;charset=ISO-8859-1")) .andExpect(content().string("Callable result")); }
Example #22
Source File: ServiceTest.java From WeEvent with Apache License 2.0 | 5 votes |
@Test public void checkConditionRight6() throws Exception { String url = "/checkWhereCondition"; RequestBuilder requestBuilder = MockMvcRequestBuilders.get(url).contentType(MediaType.APPLICATION_JSON).param("payload", "{\"a\":1,\"b\":\"2018-06-30 20:00:00\",\"c\":10}").param("condition", "c<10"); MvcResult result = mockMvc.perform(requestBuilder).andDo(print()).andReturn(); log.info("result:{}", result.getResponse().getContentAsString()); assertEquals(200, result.getResponse().getStatus()); }
Example #23
Source File: GoalIntegrationTest.java From kid-bank with Apache License 2.0 | 5 votes |
@Test public void noGoalsMessageAppearsWhenThereAreNoGoals() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/goals")) .andExpect(status().isOk()) .andExpect(view().name("goals")) .andExpect(model().attributeExists("goals")) .andExpect(model().attributeExists("createGoal")) .andReturn(); assertThat(mvcResult.getResponse().getContentAsString()) .contains("There are no currently active Goals.") .contains("<form method=\"post\" action=\"/goals/create\">") .doesNotContain("<th>Goal</th>"); }
Example #24
Source File: MockMvcApiTest.java From spring-boot-cookbook with Apache License 2.0 | 5 votes |
@Test public void testUserInfo() throws Exception { String uri = "/user/1"; MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)) .andReturn(); int status = result.getResponse().getStatus(); assertThat("正确的返回值为200", 200, is(status)); String content = result.getResponse().getContentAsString(); assertThat(content, is(expectedJson)); }
Example #25
Source File: ApiV2ControllerMultReferenceTest.java From we-cmdb with Apache License 2.0 | 5 votes |
private void queryMultiReferenceAndVerify(int ciTypeId, String refField, int expectReferenceCount) throws Exception, UnsupportedEncodingException, IOException { MvcResult mvcResult; String retContent; mvcResult = mvc.perform(post("/api/v2/ci/{ciTypeId}/retrieve", ciTypeId).contentType(MediaType.APPLICATION_JSON) .content("{}")) .andExpect(jsonPath("$.statusCode", is("OK"))) .andReturn(); retContent = mvcResult.getResponse() .getContentAsString(); assertThat(JsonUtil.asNodeByPath(retContent, "/data/contents") .size(), equalTo(1)); assertThat(JsonUtil.asNodeByPath(retContent, "/data/contents/0/data/" + refField) .size(), equalTo(expectReferenceCount)); }
Example #26
Source File: ConsumerDemoApplicationTests.java From lion with Apache License 2.0 | 5 votes |
@Test public void mockTestBlockChainMined() throws Exception { MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.post("/blockchain/mined") .param("data", "lion") .accept(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); System.out.println(mvcResult); }
Example #27
Source File: GetMetricValuesOfCommitControllerTest.java From coderadar with MIT License | 5 votes |
@Test void checkMetricsAreCalculatedCorrectlyForSecondCommit() throws Exception { GetMetricValuesOfCommitCommand command = new GetMetricValuesOfCommitCommand(); command.setMetrics( Arrays.asList( "coderadar:size:loc:java", "coderadar:size:sloc:java", "coderadar:size:cloc:java", "coderadar:size:eloc:java")); command.setCommit("2c37909c99f4518302484c646db16ce1b22b0762"); MvcResult result = mvc() .perform( get("/api/projects/" + projectId + "/metricvalues/perCommit") .contentType(MediaType.APPLICATION_JSON) .content(toJson(command))) .andReturn(); List<MetricValueForCommit> metricValuesForCommit = fromJson( new TypeReference<List<MetricValueForCommit>>() {}, result.getResponse().getContentAsString()); Assertions.assertEquals(3L, metricValuesForCommit.size()); Assertions.assertEquals(15L, metricValuesForCommit.get(0).getValue()); Assertions.assertEquals(27L, metricValuesForCommit.get(1).getValue()); Assertions.assertEquals(21L, metricValuesForCommit.get(2).getValue()); }
Example #28
Source File: FlashAttributeResultMatchers.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Assert a flash attribute's value with the given Hamcrest {@link Matcher}. */ public <T> ResultMatcher attribute(final String name, final Matcher<T> matcher) { return new ResultMatcher() { @Override @SuppressWarnings("unchecked") public void match(MvcResult result) throws Exception { assertThat("Flash attribute", (T) result.getFlashMap().get(name), matcher); } }; }
Example #29
Source File: ConsumerDemoApplicationTests.java From lion with Apache License 2.0 | 5 votes |
@Test public void mockTestTempOrderRollback() throws Exception { MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.post("/temp/order/rollback") .accept(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); System.out.println(mvcResult); }
Example #30
Source File: CatalogControllerIntegrationTest.java From spring-cloud-open-service-broker with Apache License 2.0 | 5 votes |
@Test void catalogIsRetrieved() throws Exception { MvcResult mvcResult = this.mockMvc.perform(get("/v2/catalog") .accept(MediaType.APPLICATION_JSON)) .andExpect(request().asyncStarted()) .andReturn(); assertResult(mvcResult); }