本文整理匯總了Java中org.springframework.boot.test.web.client.TestRestTemplate類的典型用法代碼示例。如果您正苦於以下問題:Java TestRestTemplate類的具體用法?Java TestRestTemplate怎麽用?Java TestRestTemplate使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
TestRestTemplate類屬於org.springframework.boot.test.web.client包,在下文中一共展示了TestRestTemplate類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: beforeClass
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@BeforeClass
public static void beforeClass() throws Exception {
jettyServer = new Server(0);
WebAppContext webApp = new WebAppContext();
webApp.setServer(jettyServer);
webApp.setContextPath(CONTEXT_PATH);
webApp.setWar("src/test/webapp");
jettyServer.setHandler(webApp);
jettyServer.start();
serverPort = ((ServerConnector)jettyServer.getConnectors()[0]).getLocalPort();
testRestTemplate = new TestRestTemplate(new RestTemplateBuilder()
.rootUri("http://localhost:" + serverPort + CONTEXT_PATH));
}
示例2: 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));
}
示例3: getJwtTokenByImplicitGrant
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@Test
public void getJwtTokenByImplicitGrant() throws JsonParseException, JsonMappingException, IOException {
String redirectUrl = "http://localhost:"+port+"/resources/user";
ResponseEntity<String> response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port
+ "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}", null, String.class,redirectUrl);
assertEquals(HttpStatus.OK, response.getStatusCode());
List<String> setCookie = response.getHeaders().get("Set-Cookie");
String jSessionIdCookie = setCookie.get(0);
String cookieValue = jSessionIdCookie.split(";")[0];
HttpHeaders headers = new HttpHeaders();
headers.add("Cookie", cookieValue);
response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port
+ "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize",
new HttpEntity<>(headers), String.class, redirectUrl);
assertEquals(HttpStatus.FOUND, response.getStatusCode());
assertNull(response.getBody());
String location = response.getHeaders().get("Location").get(0);
//FIXME: Is this a bug with redirect URL?
location = location.replace("#", "?");
response = new TestRestTemplate().getForEntity(location, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
示例4: getJwtTokenByClientCredentialForUser
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForUser() throws JsonParseException, JsonMappingException, IOException {
ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=user&password=password", null, String.class);
String responseText = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
assertEquals("bearer", jwtMap.get("token_type"));
assertEquals("read write", jwtMap.get("scope"));
assertTrue(jwtMap.containsKey("access_token"));
assertTrue(jwtMap.containsKey("expires_in"));
assertTrue(jwtMap.containsKey("jti"));
String accessToken = (String) jwtMap.get("access_token");
Jwt jwtToken = JwtHelper.decode(accessToken);
String claims = jwtToken.getClaims();
HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
assertEquals("trusted-app", claimsMap.get("client_id"));
assertEquals("user", claimsMap.get("user_name"));
assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
assertEquals("ROLE_USER", ((List<String>) claimsMap.get("authorities")).get(0));
}
開發者ID:leftso,項目名稱:demo-spring-boot-security-oauth2,代碼行數:26,代碼來源:GrantByResourceOwnerPasswordCredentialTest.java
示例5: getJwtTokenByClientCredentialForAdmin
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForAdmin() throws JsonParseException, JsonMappingException, IOException {
ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class);
String responseText = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
assertEquals("bearer", jwtMap.get("token_type"));
assertEquals("read write", jwtMap.get("scope"));
assertTrue(jwtMap.containsKey("access_token"));
assertTrue(jwtMap.containsKey("expires_in"));
assertTrue(jwtMap.containsKey("jti"));
String accessToken = (String) jwtMap.get("access_token");
Jwt jwtToken = JwtHelper.decode(accessToken);
String claims = jwtToken.getClaims();
HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
assertEquals("trusted-app", claimsMap.get("client_id"));
assertEquals("admin", claimsMap.get("user_name"));
assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
assertEquals("ROLE_ADMIN", ((List<String>) claimsMap.get("authorities")).get(0));
}
開發者ID:leftso,項目名稱:demo-spring-boot-security-oauth2,代碼行數:26,代碼來源:GrantByResourceOwnerPasswordCredentialTest.java
示例6: accessProtectedResourceByJwtTokenForUser
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@Test
public void accessProtectedResourceByJwtTokenForUser() throws JsonParseException, JsonMappingException, IOException {
ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/user", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=user&password=password", null, String.class);
String responseText = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
String accessToken = (String) jwtMap.get("access_token");
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + accessToken);
response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/user", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals("user", response.getBody());
response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals("[{\"authority\":\"ROLE_USER\"}]", response.getBody());
}
開發者ID:leftso,項目名稱:demo-spring-boot-security-oauth2,代碼行數:24,代碼來源:GrantByResourceOwnerPasswordCredentialTest.java
示例7: accessProtectedResourceByJwtTokenForAdmin
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@Test
public void accessProtectedResourceByJwtTokenForAdmin() throws JsonParseException, JsonMappingException, IOException {
ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/admin", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class);
String responseText = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
String accessToken = (String) jwtMap.get("access_token");
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + accessToken);
response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/admin", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals("admin", response.getBody());
response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals("[{\"authority\":\"ROLE_ADMIN\"}]", response.getBody());
}
開發者ID:leftso,項目名稱:demo-spring-boot-security-oauth2,代碼行數:24,代碼來源:GrantByResourceOwnerPasswordCredentialTest.java
示例8: dashboardLoads
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@Test
public void dashboardLoads() {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.port + "/dashboard", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
String body = entity.getBody();
// System.err.println(body);
assertTrue(body.contains("eureka/js"));
assertTrue(body.contains("eureka/css"));
// The "DS Replicas"
assertTrue(
body.contains("<a href=\"http://localhost:8761/eureka/\">localhost</a>"));
// The Home
assertTrue(body.contains("<a href=\"/dashboard\">Home</a>"));
// The Lastn
assertTrue(body.contains("<a href=\"/dashboard/lastn\">Last"));
}
示例9: testTraces
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@Test(timeout = 180000)
public void testTraces() throws Exception {
waitForAppsToStart();
String uri = "http://localhost:" + shoppingCart.port() + "/checkout";
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
assertEquals("{\"message\":\"order processed successfully\"}", response.getBody());
Trace shoppingCartTrace = shoppingCart.getTrace();
Trace ordersTrace = orders.getTrace();
Trace paymentsTrace = payments.getTrace();
assertThat(paymentsTrace.getTraceId()).isEqualTo(shoppingCartTrace.getTraceId());
assertThat(ordersTrace.getTraceId()).isEqualTo(shoppingCartTrace.getTraceId());
assertThat(paymentsTrace.getParentSpanId()).isEqualTo(ordersTrace.getSpanId());
assertThat(ordersTrace.getParentSpanId()).isEqualTo(shoppingCartTrace.getSpanId());
assertThat(shoppingCartTrace.getSpanId()).isNotEqualTo(ordersTrace.getSpanId());
assertThat(ordersTrace.getSpanId()).isNotEqualTo(paymentsTrace.getSpanId());
}
示例10: testPassword
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@Test
public void testPassword() throws IOException {
String tokenUrl = authUrlPrefix + "/oauth/token?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=password&username=" + username + "&password=" + password;
HttpHeaders headers1 = null;
//headers1 = AuthorizationUtil.basic("admin","admin");
ResponseEntity<String> response = new TestRestTemplate().postForEntity(tokenUrl, null, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap map = new ObjectMapper().readValue(response.getBody(), HashMap.class);
String accessToken = (String) map.get("access_token");
String refreshToken = (String) map.get("refresh_token");
System.out.println("Token Info:" + map.toString());
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + accessToken);
response = new TestRestTemplate().exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("secure", new ObjectMapper().readValue(response.getBody(), HashMap.class).get("content"));
refreshToken(refreshToken);
}
示例11: testImplicit
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@Test
public void testImplicit() throws IOException {
unauthorizedRequest();
String authUrl = authBasicUrlPrefix + "/oauth/authorize?response_type=token&client_id=" + clientId + "&redirect_uri=" + resourceUrl;
HttpHeaders headers1 = null;
headers1 = AuthorizationUtil.basic("admin", "admin");
ResponseEntity<String> response = new TestRestTemplate().postForEntity(authUrl, new HttpEntity<>(headers1), null, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
String cookieValue = response.getHeaders().get("Set-Cookie").get(0).split(";")[0];
HttpHeaders headers = new HttpHeaders();
headers.add("Cookie", cookieValue);
authUrl = authUrlPrefix + "/oauth/authorize?user_oauth_approval=true&scope.read=true";
response = new TestRestTemplate().postForEntity(authUrl, new HttpEntity<>(headers), String.class);
assertEquals(HttpStatus.FOUND, response.getStatusCode());
String location = response.getHeaders().get("Location").get(0).replace("#", "?");
System.out.println("Token Info For Location:" + location);
response = new TestRestTemplate().getForEntity(location, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("secure", new ObjectMapper().readValue(response.getBody(), HashMap.class).get("content"));
}
示例12: 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")));
}
示例13: testMetricsIsSecure
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@Test
public void testMetricsIsSecure() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port + "/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port + "/metrics/", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.port + "/metrics/foo", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.port + "/metrics.json", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:17,代碼來源:SampleActuatorApplicationTests.java
示例14: testLogin
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
@Test
public void testLogin() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("username", "admin");
form.set("password", "admin");
getCsrf(form, headers);
ResponseEntity<String> entity = new TestRestTemplate().exchange(
"http://localhost:" + this.port + "/login", HttpMethod.POST,
new HttpEntity<MultiValueMap<String, String>>(form, headers),
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND);
assertThat(entity.getHeaders().getLocation().toString())
.isEqualTo("http://localhost:" + this.port + "/");
}
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:17,代碼來源:SampleMethodSecurityApplicationTests.java
示例15: printAccessToken
import org.springframework.boot.test.web.client.TestRestTemplate; //導入依賴的package包/類
private void printAccessToken(String authServerURL, String userId, String userPassword) throws IOException {
String encodedPassword = null;
try {
encodedPassword = URLEncoder.encode(userPassword, "UTF-8");
} catch (UnsupportedEncodingException e) {
return;
}
String url = authServerURL + "/oauth/token?grant_type=password&username=" + userId + "&password=" + encodedPassword;
ResponseEntity<String> responseEntity = new TestRestTemplate(
"trusted-sw360-client",
"sw360-secret")
.postForEntity(url,
null,
String.class);
String responseBody = responseEntity.getBody();
JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody);
assertThat(responseBodyJsonNode.has("access_token"), is(true));
String accessToken = responseBodyJsonNode.get("access_token").asText();
System.out.println("Authorization: Bearer " + accessToken);
}