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


Java TestRestTemplate.exchange方法代碼示例

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


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

示例1: testPushTaupageLog

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
@Test
public void testPushTaupageLog() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD);

    stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201)));

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);
    assertThat(response.getStatusCode()).isEqualTo(CREATED);

    log.debug("Waiting for async tasks to finish");
    TimeUnit.SECONDS.sleep(1);

    verify(postRequestedFor(urlPathEqualTo("/api/instance-logs"))
                   .withRequestBody(equalToJson(intanceLogsJsonPayload))
                   .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));

    verify(putRequestedFor(urlPathEqualTo("/events/" + eventID))
                   .withRequestBody(equalToJson(new String(auditTrailJsonPayload)))
                   .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));

    log.info("METRICS:\n{}",
             restOperations.getForObject("http://localhost:" + managementPort + "/metrics", String.class));
}
 
開發者ID:zalando-stups,項目名稱:log-sink,代碼行數:27,代碼來源:LogSinkAppIT.java

示例2: testPushTaupageLogWithRetry

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
@Test
public void testPushTaupageLogWithRetry() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD);

    stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201).withFixedDelay(100)));
    stubFor(put(urlEqualTo("/events/" + eventID)).willReturn(aResponse().withStatus(429).withFixedDelay(100)));

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);
    assertThat(response.getStatusCode()).isEqualTo(CREATED);

    log.debug("Waiting for async tasks to finish");
    TimeUnit.MILLISECONDS.sleep(7500);

    verify(postRequestedFor(urlPathEqualTo("/api/instance-logs"))
                   .withRequestBody(equalToJson(intanceLogsJsonPayload))
                   .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));

    verify(3, putRequestedFor(urlPathEqualTo("/events/" + eventID))
            .withRequestBody(equalToJson(new String(auditTrailJsonPayload)))
            .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));
}
 
開發者ID:zalando-stups,項目名稱:log-sink,代碼行數:25,代碼來源:LogSinkAppIT.java

示例3: testPushStandardLog

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
@Test
public void testPushStandardLog() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD);

    stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201)));

    //change the log type to something different than 'USER_DATA' to avoid sending an audit trail event
    instanceLogsPayload.put("log_type", "SOMETHING_DIFFERENT");

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);
    assertThat(response.getStatusCode()).isEqualTo(CREATED);

    log.debug("Waiting for async tasks to finish");
    TimeUnit.SECONDS.sleep(1);

    final String standardLogsPayload = objectMapper.writeValueAsString(instanceLogsPayload);
    verify(postRequestedFor(urlPathEqualTo("/api/instance-logs"))
                   .withRequestBody(equalToJson(standardLogsPayload))
                   .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));

    verify(0, putRequestedFor(urlPathMatching("/events/.*")));
}
 
開發者ID:zalando-stups,項目名稱:log-sink,代碼行數:26,代碼來源:LogSinkAppIT.java

示例4: testPushLogsUnauthenticated

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
@Test
public void testPushLogsUnauthenticated() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate();

    stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201)));

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);
    assertThat(response.getStatusCode()).isEqualTo(UNAUTHORIZED);
}
 
開發者ID:zalando-stups,項目名稱:log-sink,代碼行數:13,代碼來源:LogSinkAppIT.java

示例5: testPushLogsWrongPassword

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
@Test
public void testPushLogsWrongPassword() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, "wrong-password");

    stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201)));

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);
    assertThat(response.getStatusCode()).isEqualTo(UNAUTHORIZED);
}
 
開發者ID:zalando-stups,項目名稱:log-sink,代碼行數:13,代碼來源:LogSinkAppIT.java

示例6: testPushLogsUpstreamFailsOnce

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
@Test
public void testPushLogsUpstreamFailsOnce() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD);

    // first calls fails
    stubFor(post(urlPathEqualTo("/api/instance-logs")).inScenario("Test Retry")
                    .whenScenarioStateIs(STARTED)
                    .willReturn(aResponse().withStatus(500))
                    .willSetStateTo("retry"));

    // second one succeeds
    stubFor(post(urlPathEqualTo("/api/instance-logs")).inScenario("Test Retry")
                    .whenScenarioStateIs("retry")
                    .willReturn(aResponse().withStatus(201)));

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);

    // even if upstream request fails, due to async processing this endpoint should return a success message
    assertThat(response.getStatusCode()).isEqualTo(CREATED);

    log.debug("Waiting for async tasks to finish");
    TimeUnit.SECONDS.sleep(2);

    // endpoint should have been called twice
    verify(2, postRequestedFor(urlPathEqualTo("/api/instance-logs"))
            .withRequestBody(equalToJson(intanceLogsJsonPayload))
            .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));
}
 
開發者ID:zalando-stups,項目名稱:log-sink,代碼行數:32,代碼來源:LogSinkAppIT.java

示例7: testCompression

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
@Test
public void testCompression() throws Exception {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("Accept-Encoding", "gzip");
	HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
	TestRestTemplate restTemplate = new TestRestTemplate();
	ResponseEntity<byte[]> entity = restTemplate.exchange(
			"http://localhost:" + this.port, HttpMethod.GET, requestEntity,
			byte[].class);
	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
	GZIPInputStream inflater = new GZIPInputStream(
			new ByteArrayInputStream(entity.getBody()));
	try {
		assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8")))
				.isEqualTo("Hello World");
	}
	finally {
		inflater.close();
	}
}
 
開發者ID:philwebb,項目名稱:spring-boot-concourse,代碼行數:21,代碼來源:SampleJetty8ApplicationTests.java

示例8: testAuditLogDataIsObfuscated

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
@Test
public void testAuditLogDataIsObfuscated() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD);

    stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201)));

    instanceLogsPayload.put("log_type", "AUDIT_LOG");

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);
    assertThat(response.getStatusCode()).isEqualTo(CREATED);

    log.debug("Waiting for async tasks to finish");
    TimeUnit.SECONDS.sleep(1);

    assertThat(capture.toString()).contains("\"log_data\":\"***\"");
}
 
開發者ID:zalando-stups,項目名稱:log-sink,代碼行數:20,代碼來源:LogSinkAppIT.java

示例9: testCompression

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
@Test
public void testCompression() throws Exception {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("Accept-Encoding", "gzip");
	HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

	TestRestTemplate restTemplate = new TestRestTemplate();

	ResponseEntity<byte[]> entity = restTemplate.exchange(
			"http://localhost:" + this.port, HttpMethod.GET, requestEntity,
			byte[].class);

	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);

	GZIPInputStream inflater = new GZIPInputStream(
			new ByteArrayInputStream(entity.getBody()));
	try {
		assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8")))
				.isEqualTo("Hello World");
	}
	finally {
		inflater.close();
	}
}
 
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:25,代碼來源:SampleJettyApplicationTests.java

示例10: verifyAuthentication

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) {
	String baseUrl = "http://localhost:" + this.context.getWebServer().getPort();
	TestRestTemplate rest = new TestRestTemplate();
	// First, verify the web endpoint can't be reached
	assertEndpointUnauthorized(baseUrl, rest);
	// Since we can't reach it, need to collect an authorization token
	HttpHeaders headers = getHeaders(config);
	String url = baseUrl + "/oauth/token";
	JsonNode tokenResponse = rest.postForObject(url,
			new HttpEntity<>(getBody(), headers), JsonNode.class);
	String authorizationToken = tokenResponse.findValue("access_token").asText();
	String tokenType = tokenResponse.findValue("token_type").asText();
	String scope = tokenResponse.findValues("scope").get(0).toString();
	assertThat(tokenType).isEqualTo("bearer");
	assertThat(scope).isEqualTo("\"read\"");
	// Now we should be able to see that endpoint.
	headers.set("Authorization", "BEARER " + authorizationToken);
	ResponseEntity<String> securedResponse = rest
			.exchange(new RequestEntity<Void>(headers, HttpMethod.GET,
					URI.create(baseUrl + "/securedFind")), String.class);
	assertThat(securedResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
	assertThat(securedResponse.getBody()).isEqualTo(
			"You reached an endpoint " + "secured by Spring Security OAuth2");
	ResponseEntity<String> entity = rest.exchange(new RequestEntity<Void>(headers,
			HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class);
	assertThat(entity.getStatusCode()).isEqualTo(finalStatus);
}
 
開發者ID:spring-projects,項目名稱:spring-security-oauth2-boot,代碼行數:28,代碼來源:OAuth2AutoConfigurationTests.java

示例11: method

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
/**
 * Make an api call to /users.
 */
@When("^I request resource \"([/\\w]+)\" with method ([\\w]+)$")
public void i_request_resource_with_method(String endpoint, String method) {
	TestRestTemplate template = restTemplate;

	if (authenticationWorld.haveCredentials()) {
		template = restTemplate.withBasicAuth(authenticationWorld.getUsername(), authenticationWorld.getPassword());
	}

	ResponseEntity<String> response = template.exchange(endpoint, HttpMethod.valueOf(method), null, String.class);
	httpWorld.saveResponse(response);
}
 
開發者ID:cmateosl,項目名稱:role-api,代碼行數:15,代碼來源:HttpSteps.java

示例12: verifyAuthentication

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) {
	String baseUrl = "http://localhost:"
			+ this.context.getEmbeddedServletContainer().getPort();
	TestRestTemplate rest = new TestRestTemplate();
	// First, verify the web endpoint can't be reached
	assertEndpointUnauthorized(baseUrl, rest);
	// Since we can't reach it, need to collect an authorization token
	HttpHeaders headers = getHeaders(config);
	String url = baseUrl + "/oauth/token";
	JsonNode tokenResponse = rest.postForObject(url,
			new HttpEntity<MultiValueMap<String, Object>>(getBody(), headers),
			JsonNode.class);
	String authorizationToken = tokenResponse.findValue("access_token").asText();
	String tokenType = tokenResponse.findValue("token_type").asText();
	String scope = tokenResponse.findValues("scope").get(0).toString();
	assertThat(tokenType).isEqualTo("bearer");
	assertThat(scope).isEqualTo("\"read\"");
	// Now we should be able to see that endpoint.
	headers.set("Authorization", "BEARER " + authorizationToken);
	ResponseEntity<String> securedResponse = rest
			.exchange(new RequestEntity<Void>(headers, HttpMethod.GET,
					URI.create(baseUrl + "/securedFind")), String.class);
	assertThat(securedResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
	assertThat(securedResponse.getBody()).isEqualTo(
			"You reached an endpoint " + "secured by Spring Security OAuth2");
	ResponseEntity<String> entity = rest.exchange(new RequestEntity<Void>(headers,
			HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class);
	assertThat(entity.getStatusCode()).isEqualTo(finalStatus);
}
 
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:30,代碼來源:OAuth2AutoConfigurationTests.java

示例13: assertEndpointUnauthorized

import org.springframework.boot.test.web.client.TestRestTemplate; //導入方法依賴的package包/類
private void assertEndpointUnauthorized(String baseUrl, TestRestTemplate rest) {
	URI uri = URI.create(baseUrl + "/secured");
	ResponseEntity<String> entity = rest
			.exchange(new RequestEntity<Void>(HttpMethod.GET, uri), String.class);
	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
 
開發者ID:spring-projects,項目名稱:spring-security-oauth2-boot,代碼行數:7,代碼來源:OAuth2AutoConfigurationTests.java


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