當前位置: 首頁>>代碼示例>>Java>>正文


Java MvcResult.getResponse方法代碼示例

本文整理匯總了Java中org.springframework.test.web.servlet.MvcResult.getResponse方法的典型用法代碼示例。如果您正苦於以下問題:Java MvcResult.getResponse方法的具體用法?Java MvcResult.getResponse怎麽用?Java MvcResult.getResponse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.springframework.test.web.servlet.MvcResult的用法示例。


在下文中一共展示了MvcResult.getResponse方法的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getTransformationProperties

import org.springframework.test.web.servlet.MvcResult; //導入方法依賴的package包/類
@Test
public void getTransformationProperties() throws Exception {
    preInitNonCreationTests();
    MvcResult result = mvc.perform(
        get(GET_PROPERTIES_VALID_URL)
    ).andDo(print())
        .andExpect(status().is(200))
        .andExpect(content().contentType(DEFAULT_CHARSET_HAL_JSON))
        .andExpect(jsonPath("$.properties").isArray())
        .andExpect(jsonPath("$.properties").isNotEmpty())
        .andExpect(jsonPath("$.properties[0].key").isString())
        .andExpect(jsonPath("$.properties[0].type").isString())
        .andExpect(jsonPath("$.properties[0].description").isString())
        .andExpect(jsonPath("$.properties[0].required").isBoolean())
        .andExpect(jsonPath("$.links[0].rel").value("self"))
        .andExpect(jsonPath("$.links[0].href")
            .value("http://localhost/api/csars/kubernetes-cluster/transformations/p-a/properties"))
        .andReturn();

    MockHttpServletResponse response = result.getResponse();
    String responseJson = new String(response.getContentAsByteArray());
    String[] values = JsonPath.parse(responseJson).read("$.properties[*].value", String[].class);
    long nullCount = Arrays.asList(values).stream().filter(Objects::isNull).count();
    long testCount = Arrays.asList(values).stream().filter(e -> e != null && e.equals(PROPERTY_TEST_DEFAULT_VALUE)).count();
    assertEquals(7, nullCount);
    assertEquals(1, testCount);
}
 
開發者ID:StuPro-TOSCAna,項目名稱:TOSCAna,代碼行數:28,代碼來源:TransformationControllerTest.java

示例2: createJsonFileFromSwaggerEndpoint

import org.springframework.test.web.servlet.MvcResult; //導入方法依賴的package包/類
@Test
public void createJsonFileFromSwaggerEndpoint() throws Exception {
    String outputDir = Optional.ofNullable(System.getProperty("io.springfox.staticdocs.outputDir"))
            .orElse("build/swagger");
    System.err.println(outputDir);
    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"),
            StandardCharsets.UTF_8)) {
        writer.write(swaggerJson);
    }
}
 
開發者ID:tsypuk,項目名稱:springrestdoc,代碼行數:19,代碼來源:Swagger2MarkupTest.java

示例3: Should_ReturnErrorMessage_ForUnmatchingUser

import org.springframework.test.web.servlet.MvcResult; //導入方法依賴的package包/類
@Test
@DisplayName("Should return error message for when user not existing in the database tries to login.")
public void Should_ReturnErrorMessage_ForUnmatchingUser() throws Exception {
	
	User user = new User();
	user.setEmail("[email protected]");
	user.setPassword("foobar");
	//
	// Create JSON Representation for User object;
	// Gson is a Java serialization/deserialization library to 
	// convert Java Objects into JSON and back
	//
	Gson gson = new Gson();
	String jsonUser = gson.toJson(user);
	//
	// Mock the isValidUser method of userService
	//
	Mockito.when(this.userService.isValidUser("[email protected]", "foobar")).thenReturn(null);
	//
	// Invoke the method
	//
	MvcResult result = this.mockMvc.perform(
            post("/account/login/process")
            .contentType(MediaType.APPLICATION_JSON)
            .content(jsonUser))
			.andExpect(status().isOk())
            .andReturn();
	
	MockHttpServletResponse response  = result.getResponse();
	ObjectMapper mapper = new ObjectMapper();
	ExecutionStatus responseObj = mapper.readValue(response.getContentAsString(), ExecutionStatus.class);
    assertTrue(responseObj.getCode().equals("USER_LOGIN_UNSUCCESSFUL"));
    assertTrue(responseObj.getMessage().equals("Username or password is incorrect. Please try again!"));
}
 
開發者ID:PacktPublishing,項目名稱:Building-Web-Apps-with-Spring-5-and-Angular,代碼行數:35,代碼來源:UserAccountControllerTest.java

示例4: handle

import org.springframework.test.web.servlet.MvcResult; //導入方法依賴的package包/類
@Override
public void handle(MvcResult result) throws Exception {
    MockHttpServletRequest request = result.getRequest();
    MockHttpServletResponse response = result.getResponse();
    logger.error("HTTP method: {}, status code: {}", request.getMethod(), response.getStatus());
}
 
開發者ID:tsypuk,項目名稱:springrestdoc,代碼行數:7,代碼來源:MyResultHandler.java

示例5: should_upload_and_download_zipped_log

import org.springframework.test.web.servlet.MvcResult; //導入方法依賴的package包/類
@Test
public void should_upload_and_download_zipped_log() throws Throwable {
    // given:
    ClassLoader classLoader = CmdControllerTest.class.getClassLoader();
    URL resource = classLoader.getResource("test-cmd-id.out.zip");
    Path path = Paths.get(resource.getFile());
    byte[] data = Files.readAllBytes(path);

    CmdInfo cmdBase = new CmdInfo("test-zone-1", "test-agent-1", CmdType.RUN_SHELL, "~/hello.sh");
    Cmd cmd = cmdService.create(cmdBase);

    String originalFilename = cmd.getId() + ".out.zip";

    MockMultipartFile zippedCmdLogPart = new MockMultipartFile("file", originalFilename, "application/zip", data);
    MockMultipartFile cmdIdPart = new MockMultipartFile("cmdId", "", "text/plain", cmd.getId().getBytes());

    // when: upload zipped cmd log
    MockMultipartHttpServletRequestBuilder content = fileUpload("/cmd/log/upload")
        .file(zippedCmdLogPart)
        .file(cmdIdPart);

    this.mockMvc.perform(content)
        .andDo(print())
        .andExpect(status().isOk());

    // then: check upload file path and logging queue
    Path zippedLogPath = Paths.get(cmdLogDir.toString(), originalFilename);
    Assert.assertTrue(Files.exists(zippedLogPath));
    Assert.assertEquals(data.length, Files.size(zippedLogPath));

    // when: download uploaded zipped cmd log
    MvcResult result = this.mockMvc.perform(get("/cmd/log/download")
        .param("cmdId", cmd.getId()).param("index", Integer.toString(0)))
        .andDo(print())
        .andExpect(status().isOk())
        .andReturn();

    // then:
    MockHttpServletResponse response = result.getResponse();
    Assert.assertEquals("application/zip", response.getContentType());
    Assert.assertEquals(data.length, response.getContentLength());
    Assert.assertTrue(response.getHeader("Content-Disposition").contains(originalFilename));
}
 
開發者ID:FlowCI,項目名稱:flow-platform,代碼行數:44,代碼來源:CmdControllerTest.java


注:本文中的org.springframework.test.web.servlet.MvcResult.getResponse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。