org.mockito.verification.VerificationMode#org.springframework.test.web.servlet.MvcResult源码实例Demo

下面列出了org.mockito.verification.VerificationMode#org.springframework.test.web.servlet.MvcResult 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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);
}
 
@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);
}
 
@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" ) );

}
 
源代码4 项目: Mahuta   文件: ConfigControllerTest.java
@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());
}
 
@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")));
}
 
@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"));
}
 
源代码7 项目: spring-examples   文件: KisiControllerTest.java
@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);
}
 
源代码8 项目: full-teaching   文件: FileTestUtils.java
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;
}
 
@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"));
}
 
@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);
}
 
源代码11 项目: blue-marlin   文件: TestIMSController.java
@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());
}
 
@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();
}
 
@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" ) );

}
 
@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);
}
 
源代码15 项目: hawkbit   文件: MgmtTargetResourceTest.java
@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());
}
 
@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);
}
 
源代码17 项目: exchange-gateway-rest   文件: TestService.java
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();
    }
 
@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);
}
 
@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);
}
 
/**
 * 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);
		}
	};
}
 
源代码21 项目: spring-tutorial   文件: CallableControllerTests.java
@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"));
}
 
源代码22 项目: WeEvent   文件: ServiceTest.java
@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());
}
 
源代码23 项目: kid-bank   文件: GoalIntegrationTest.java
@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>");
}
 
源代码24 项目: spring-boot-cookbook   文件: MockMvcApiTest.java
@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));
}
 
源代码25 项目: we-cmdb   文件: ApiV2ControllerMultReferenceTest.java
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));
}
 
源代码26 项目: lion   文件: ConsumerDemoApplicationTests.java
@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);
}
 
@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());
}
 
/**
 * 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);
		}
	};
}
 
源代码29 项目: lion   文件: ConsumerDemoApplicationTests.java
@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);
}
 
@Test
void catalogIsRetrieved() throws Exception {
	MvcResult mvcResult = this.mockMvc.perform(get("/v2/catalog")
			.accept(MediaType.APPLICATION_JSON))
			.andExpect(request().asyncStarted())
			.andReturn();
	assertResult(mvcResult);
}