下面列出了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" ) );
}
@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"));
}
@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);
}
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);
}
@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);
}
@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);
}
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);
}
};
}
@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"));
}
@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());
}
@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>");
}
@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));
}
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));
}
@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);
}
};
}
@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);
}