本文整理匯總了Java中org.springframework.test.web.servlet.MvcResult類的典型用法代碼示例。如果您正苦於以下問題:Java MvcResult類的具體用法?Java MvcResult怎麽用?Java MvcResult使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
MvcResult類屬於org.springframework.test.web.servlet包,在下文中一共展示了MvcResult類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testGetUsersPage0Size20
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void testGetUsersPage0Size20() throws Exception {
final MvcResult mvcResult = mockMvc
.perform(get(UserController.REQUEST_PATH_API_USERS).accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.request().asyncStarted())
.andReturn();
mockMvc
.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.content", Matchers.hasSize(2)))
.andExpect(jsonPath("$.content[0].email").value("[email protected]"))
.andExpect(jsonPath("$.content[0].firstName").value("User"))
.andExpect(jsonPath("$.content[0].lastName").value("One"))
.andExpect(jsonPath("$.content[1].email").value("[email protected]"))
.andExpect(jsonPath("$.content[1].firstName").value("User"))
.andExpect(jsonPath("$.content[1].lastName").value("Two"))
.andExpect(jsonPath("$.totalElements").value(2))
.andExpect(jsonPath("$.totalPages").value(1))
.andExpect(jsonPath("$.size").value(20))
.andExpect(jsonPath("$.number").value(0))
.andExpect(jsonPath("$.first").value("true"))
.andExpect(jsonPath("$.last").value("true"));
}
示例2: should_get_the_preset_shop_list
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void should_get_the_preset_shop_list() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/api/shops")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
List<ShopResponse> shops = this.objectMapper.readValue(
mvcResult.getResponse().getContentAsByteArray(),
new TypeReference<List<ShopResponse>>(){});
assertEquals(1, shops.size());
ShopResponse shop = shops.get(0);
assertEquals(shopName, shop.getName());
}
示例3: should_download_success
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void should_download_success() throws Exception {
String response = performRequestWith200Status(get("/credentials"));
Credential[] credentials = Jsonable.parseArray(response, Credential[].class);
Assert.assertEquals(4, credentials.length);
response = performRequestWith200Status(get("/credentials/rsa-credential"));
Assert.assertNotNull(response);
// when: get download file
MvcResult result = mockMvc.perform(get("/credentials/rsa-credential/download")).andExpect(status().isOk())
.andReturn();
File file = new File(String.valueOf(Paths.get(workspace.toString(), "test.zip")));
FileUtils.writeByteArrayToFile(file, result.getResponse().getContentAsByteArray());
// then: response is not null
Assert.assertNotNull(response);
// then: file is exists
Assert.assertEquals(true, file.exists());
ZipFile zipFile = new ZipFile(file);
// them: zipfile has two files
Assert.assertEquals(2, zipFile.size());
}
示例4: test8_2
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void test8_2() throws Exception {
// ResultActions actions = mockMvc.perform((post("/jsonp-fastjsonview/test8?callback=fnUpdateSome").characterEncoding(
// "UTF-8")));
// actions.andDo(print());
// actions.andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JAVASCRIPT))
// .andExpect(content().string("fnUpdateSome({\"id\":100,\"name\":\"測試\"})"));
MvcResult mvcResult = mockMvc.perform(post("/jsonp-fastjsonview/test8?callback=fnUpdateSome").characterEncoding("UTF-8"))
.andExpect(request().asyncStarted())
.andReturn();
mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentType(FastJsonHttpMessageConverter.APPLICATION_JAVASCRIPT))
.andExpect(content().string("/**/fnUpdateSome({})"));
}
示例5: changeLevelTest
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void changeLevelTest() throws Exception {
LoggerVM logger = new LoggerVM();
logger.setLevel("ERROR");
logger.setName("ROOT");
mock.perform(put("/management/logs")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(new ObjectMapper().writeValueAsString(logger)))
.andExpect(status().isNoContent());
MvcResult res = mock.perform(get("/management/logs")
.accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andReturn();
assertTrue(res.getResponse().getContentAsString().contains("\"name\":\""+logger.getName()
+"\",\"level\":\""+logger.getLevel()+"\""));
}
示例6: testFilter_withValidNotesGetCall_shouldReturnDecryptedNote
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
@WithMockUser(username="[email protected]",authorities={"ADMIN","AUTHOR"},password="none")
public void testFilter_withValidNotesGetCall_shouldReturnDecryptedNote() throws Exception {
AuthUserResponse response = new AuthUserResponse();
response.setCryptKey("sikdfyh089oay3i3ip2wr3o2rj3wio8yf");
when(userService.getUserInfoFromAuthEmail(matches("[email protected]"))).thenReturn(response);
String decryptedSecretMessage = "{\"id\":\"no1\",\"title\":\"top secret\",\"lastEdit\":null,\"archived\":false,\"content\":\"Prosciutto brisket pork turkey filet mignon landjaeger cow.\"}";
when(encryptionService.decryptNote(any(), matches(response.getCryptKey()),any()))
.thenReturn(new ByteArrayInputStream(decryptedSecretMessage.getBytes()));
MvcResult result =
mockMvc.perform(get("/api/v1/notes/existingNoteId").contentType(jsonContentType)).andReturn();
assertEquals("correct response returns 200", 200, result.getResponse().getStatus());
assertEquals("check mock-decrypted message", decryptedSecretMessage, result.getResponse().getContentAsString());
verify(encryptionService,times(1)).decryptNote(any(), matches(response.getCryptKey()),any());
}
示例7: should_load_database_info
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void should_load_database_info() throws Throwable {
// when: load db info
MvcResult result = this.mockMvc.perform(get("/sys/info/db"))
.andExpect(status().isOk())
.andReturn();
// then:
String content = result.getResponse().getContentAsString();
GroupSystemInfo dbInfo = SystemInfo.parse(content, GroupSystemInfo.class);
Assert.assertEquals(Type.DB, dbInfo.getType());
Map<String, String> mysqlInfo = dbInfo.get(DBGroupName.MYSQL);
Assert.assertNotNull(mysqlInfo);
Assert.assertEquals(5, mysqlInfo.size());
}
示例8: testPredict_11dim
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void testPredict_11dim() throws Exception
{
final String predictJson = "{" +
"\"request\": {" +
"\"ndarray\": [[1.0]]}" +
"}";
MvcResult res = mvc.perform(MockMvcRequestBuilders.post("/api/v0.1/predictions")
.accept(MediaType.APPLICATION_JSON_UTF8)
.content(predictJson)
.contentType(MediaType.APPLICATION_JSON_UTF8)).andReturn();
String response = res.getResponse().getContentAsString();
System.out.println(response);
Assert.assertEquals(200, res.getResponse().getStatus());
}
示例9: should_list_all_online_agent
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void should_list_all_online_agent() throws Throwable {
// given:
String zoneName = "test-zone-01";
zoneService.createZone(new Zone(zoneName, MOCK_CLOUD_PROVIDER_NAME));
Thread.sleep(1000);
String agentName = "act-001";
String path = ZKHelper.buildPath(zoneName, agentName);
zkClient.createEphemeral(path, null);
Thread.sleep(1000);
// when: send get request
MvcResult result = this.mockMvc.perform(get("/agents/list").param("zone", zoneName))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
// then:
String json = result.getResponse().getContentAsString();
Assert.assertNotNull(json);
Agent[] agentList = gsonConfig.fromJson(json, Agent[].class);
Assert.assertEquals(1, agentList.length);
Assert.assertEquals(agentName, agentList[0].getName());
}
示例10: shouldFailForEmptyDefence
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void shouldFailForEmptyDefence() throws Exception {
long anyClaimId = 500;
String anyDefendantId = "500";
Response response = SampleResponse.FullDefence.builder()
.withDefence("")
.build();
MvcResult result = makeRequest(anyClaimId, anyDefendantId, response)
.andExpect(status().isBadRequest())
.andReturn();
assertThat(extractErrors(result))
.hasSize(1)
.contains("defence : may not be empty");
}
示例11: getHttpResultContent
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
public static MvcResult getHttpResultContent(MockMvc mockMvc, String uri, Method method, Map<String, String> keyvals) throws Exception {
MockHttpServletRequestBuilder builder = null;
switch (method) {
case GET:
builder = MockMvcRequestBuilders.get(uri);
break;
case POST:
builder = MockMvcRequestBuilders.post(uri);
break;
case PUT:
builder = MockMvcRequestBuilders.put(uri);
break;
case DELETE:
builder = MockMvcRequestBuilders.delete(uri);
break;
default:
builder = MockMvcRequestBuilders.get(uri);
}
for (Map.Entry<String, String> entry : keyvals.entrySet()) {
builder = builder.param(entry.getKey(), entry.getValue());
}
MvcResult result = mockMvc.perform(builder.accept(MediaType.ALL)).andReturn();
// result.getResponse().getHeaderNames();
return result;
}
示例12: shouldSendStaffNotificationsForCitizenClaimIssuedEvent
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void shouldSendStaffNotificationsForCitizenClaimIssuedEvent() throws Exception {
MvcResult result = makeRequest(SampleClaimData.submittedByClaimant())
.andExpect(status().isOk())
.andReturn();
Claim savedClaim = deserializeObjectFrom(result, Claim.class);
verify(emailService).sendEmail(eq("[email protected]"), emailDataArgument.capture());
EmailData emailData = emailDataArgument.getValue();
assertThat(emailData.getTo()).isEqualTo("[email protected]");
assertThat(emailData.getSubject()).isEqualTo("Claim " + savedClaim.getReferenceNumber() + " issued");
assertThat(emailData.getMessage()).isEqualTo("Please find attached claim.");
assertThat(emailData.getAttachments()).hasSize(2)
.extracting(EmailAttachment::getFilename)
.containsExactly(savedClaim.getReferenceNumber() + "-sealed-claim.pdf",
savedClaim.getReferenceNumber() + "-defendant-pin-letter.pdf");
}
示例13: testFilter_withValidNotesPostCall_shouldSendEncryptedNote
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
@WithMockUser(username="[email protected]",authorities={"ADMIN","AUTHOR"},password="none")
public void testFilter_withValidNotesPostCall_shouldSendEncryptedNote() throws Exception {
String validPost = "{\"title\":\"new note\",\"lastEdit\":\"2012-12-12T12:12:12Z\",\"pinned\":false,\"archived\":false,\"content\":\"very very secret text\",\"userId\":1}";
notesMock.stubFor(post(urlEqualTo("/api/v1/notes")).withRequestBody(equalToJson(validPost)).willReturn(aResponse().withStatus(200)));
AuthUserResponse response = new AuthUserResponse();
response.setCryptKey("sikdfyh089oay3i3ip2wr3o2rj3wio8yf");
when(userService.getUserInfoFromAuthEmail(matches("[email protected]"))).thenReturn(response);
String encryptedMessage = "{\"title\":\"new note\",\"lastEdit\":\"2012-12-12T12:12:12Z\",\"pinned\":false,\"archived\":false,\"content\":\"some text\",\"userId\":1}";
when(encryptionService.encryptNote(any(), matches(response.getCryptKey()),any()))
.thenReturn(new ByteArrayInputStream(encryptedMessage.getBytes()));
MvcResult result =
mockMvc.perform(post("/api/v1/notes").content(encryptedMessage).contentType(jsonContentType).with(csrf())).andReturn();
assertEquals("correct response returns 200", 200, result.getResponse().getStatus());
verify(encryptionService,times(1)).encryptNote(any(), any(),any());
}
示例14: testController
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void testController () throws Exception {
MvcResult result = mockMvc.perform(get("/callSelectDept/359.json"))
.andExpect(request().asyncStarted())
.andReturn();
result.getRequest().getAsyncContext().setTimeout(5000);
result.getAsyncResult();
result= mockMvc.perform(asyncDispatch(result))
.andExpect(status().isOk())
.andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE))
.andReturn();
System.out.println(result.getResponse().getContentAsString());
}
示例15: should_auth_failure
import org.springframework.test.web.servlet.MvcResult; //導入依賴的package包/類
@Test
public void should_auth_failure() {
EmailSettingContent emailSetting = new EmailSettingContent("smtp.163.com", 465, "[email protected]");
MockHttpServletRequestBuilder content = post("/message/email/settings/auth")
.contentType(MediaType.APPLICATION_JSON)
.content(emailSetting.toJson());
try {
MvcResult mvcResult = this.mockMvc.perform(content)
.andDo(print())
.andExpect(status().is4xxClientError())
.andReturn();
String response = mvcResult.getResponse().getContentAsString();
FlowException smtpAuthResponse = Jsonable.GSON_CONFIG.fromJson(response, FlowException.class);
Assert.assertNotNull(smtpAuthResponse);
} catch (Exception e) {
e.printStackTrace();
}
}