下面列出了怎么用org.springframework.boot.test.web.client.TestRestTemplate的API类实例代码及写法,或者点击链接到github查看源代码。
@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));
}
@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());
}
@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));
}
@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));
}
@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"));
}
@Test
public void resourceEndpointsWork() {
// This request will get the file from the Git Repo
String text = new TestRestTemplate()
.getForObject(
"http://localhost:" + this.port
+ "/foo/development/composite/bar.properties",
String.class);
String expected = "foo: bar";
assertThat(expected).isEqualTo(text).as("invalid content");
// This request will get the file from the SVN Repo
text = new TestRestTemplate().getForObject("http://localhost:" + this.port
+ "/foo/development/composite/bar.properties", String.class);
assertThat(expected).isEqualTo(text).as("invalid content");
}
@Before
public void setupTraceClient() throws IOException {
this.url = String.format("http://localhost:%d/", this.port);
// Create a new RestTemplate here because the auto-wired instance has built-in instrumentation
// which interferes with us setting the 'x-cloud-trace-context' header.
this.testRestTemplate = new TestRestTemplate();
this.logClient = LoggingOptions.newBuilder()
.setProjectId(this.projectIdProvider.getProjectId())
.setCredentials(this.credentialsProvider.getCredentials())
.build()
.getService();
ManagedChannel channel = ManagedChannelBuilder
.forTarget("dns:///cloudtrace.googleapis.com")
.build();
this.traceServiceStub = TraceServiceGrpc.newBlockingStub(channel)
.withCallCredentials(MoreCallCredentials.from(this.credentialsProvider.getCredentials()));
}
@Test
public void testCompositionFunctionMapping() throws Exception {
SpringApplication.run(ApplicationConfiguration.class);
TestRestTemplate testRestTemplate = new TestRestTemplate();
String port = System.getProperty("server.port");
ResponseEntity<String> response = testRestTemplate
.postForEntity(new URI("http://localhost:" + port + "/uppercase,lowercase,reverse"), "stressed", String.class);
assertThat(response.getBody()).isEqualTo("desserts");
}
@Test
public void givenService_whenPutForObject_thenCreatedObjectIsReturned() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"),
"{\"id\":1,\"name\":\"Jim\"}");
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class);
}
@Test
public void nonStandardCodeWorks() {
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.HOST, "www.setcustomstatus.org");
ResponseEntity<String> response = new TestRestTemplate().exchange(
baseUri + "/headers", HttpMethod.GET, new HttpEntity<>(headers),
String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(432);
// https://jira.spring.io/browse/SPR-16748
/*
* testClient.get() .uri("/status/432") .exchange() .expectStatus().isEqualTo(432)
* .expectBody(String.class).isEqualTo("Failed with 432");
*/
}
@Test
public void configurationAvailable() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/app/production", Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
}
@Test
public void testBackwardsCompatibleFormatWithLabel() {
Map environment = new TestRestTemplate().getForObject(
"http://localhost:" + this.port + "/foo/development/master", Map.class);
Object value = getPropertySourceValue(environment);
assertThat(value).isInstanceOf(String.class).isEqualTo("true");
}
@Test
public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate.
HttpClientOption.ENABLE_COOKIES);
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.withBasicAuth("user", "passwd").
getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Before
public void setUp() {
when(config.getConfig(ReporterConfiguration.class).isReportSynchronously()).thenReturn(true);
restTemplate = new TestRestTemplate(new RestTemplateBuilder()
.setConnectTimeout(0)
.setReadTimeout(0)
.basicAuthorization("username", "password"));
reporter.reset();
}
@Before
public void setUp() {
MockTracer.MockInstrumentationSetup mockInstrumentationSetup = MockTracer.getOrCreateInstrumentationTracer();
config = mockInstrumentationSetup.getConfig();
reporter = mockInstrumentationSetup.getReporter();
ElasticApmAgent.initInstrumentation(mockInstrumentationSetup.getTracer(), ByteBuddyAgent.install());
restTemplate = new TestRestTemplate(new RestTemplateBuilder().setConnectTimeout(0).setReadTimeout(0));
}
@BeforeClass
public static void beforeClass() {
APPLICATION_CONTEXT.registerBean("jettyReactiveWebServerFactory", JettyReactiveWebServerFactory.class, () -> new JettyReactiveWebServerFactory(0));
APPLICATION_CONTEXT.registerBean("httpHandler", HttpHandler.class, () -> WebHttpHandlerBuilder.applicationContext(APPLICATION_CONTEXT).build());
APPLICATION_CONTEXT.registerBean("webHandler", WebHandler.class, () -> SpringWebFluxTest::handler);
APPLICATION_CONTEXT.refresh();
final int serverPort = APPLICATION_CONTEXT.getWebServer().getPort();
testRestTemplate = new TestRestTemplate(new RestTemplateBuilder().rootUri("http://127.0.0.1:" + serverPort));
}
@Test
@SuppressWarnings("unchecked")
public void contextLoads() {
Map res = new TestRestTemplate().getForObject(
"http://localhost:" + this.port + BASE_PATH + "/env/info.foo", Map.class);
assertThat(res).containsKey("propertySources");
Map<String, Object> property = (Map<String, Object>) res.get("property");
assertThat(property).containsEntry("value", "bar");
}
@Test
public void adminLoads() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().exchange(
"http://localhost:" + this.port + "/context" + BASE_PATH + "/env",
HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Before
public void setup() {
clearData();
initData();
this.baseUrl = "http://localhost:" + port;
this.restTemplate = new TestRestTemplate("admin", "test123", new HttpClientOption[]{});
}
@Test
public void testAuthenticatedHello() throws Exception {
TestRestTemplate restTemplate = new TestRestTemplate();
restTemplate.getRestTemplate()
.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpClients
.custom().setSSLSocketFactory(socketFactory()).build()));
ResponseEntity<String> httpsEntity = restTemplate
.getForEntity("https://localhost:" + this.port + "/hi", String.class);
assertThat(httpsEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(httpsEntity.getBody()).containsIgnoringCase("hello, rod");
}
@Test
public void adminLoads() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().exchange(
"http://localhost:" + this.port + "/servlet" + BASE_PATH + "/env",
HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
@SuppressWarnings("unchecked")
public void contextLoads() {
Map res = new TestRestTemplate().getForObject(
"http://localhost:" + this.port + BASE_PATH + "/env/info.foo", Map.class);
assertThat(res).containsKey("propertySources");
Map<String, Object> property = (Map<String, Object>) res.get("property");
assertThat(property).containsEntry("value", "bar");
}
@Test
public void testOk() {
ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port, String.class);
assertNotNull("response was null", response);
assertEquals("Bad status code", HttpStatus.OK, response.getStatusCode());
assertEquals("Wrong response text", "OK", response.getBody());
}
@Test
public void testFallback() {
ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/fail",
String.class);
assertNotNull("response was null", response);
assertEquals("Bad status code", HttpStatus.OK, response.getStatusCode());
assertEquals("Wrong response text", "from the fallback", response.getBody());
}
@Test
public void testCompositionFunctionMapping() throws Exception {
FunctionalSpringApplication.run(ApplicationConfiguration.class);
TestRestTemplate testRestTemplate = new TestRestTemplate();
String port = System.getProperty("server.port");
Thread.sleep(200);
ResponseEntity<String> response = testRestTemplate
.postForEntity(new URI("http://localhost:" + port + "/uppercase,lowercase,reverse"), "stressed", String.class);
assertThat(response.getBody()).isEqualTo("desserts");
}
@Test
public void hystrixStreamWorks() throws Exception {
String url = "http://localhost:" + port;
// you have to hit a Hystrix circuit breaker before the stream sends anything
ResponseEntity<String> response = new TestRestTemplate().getForEntity(url, String.class);
assertEquals("bad response code", HttpStatus.OK, response.getStatusCode());
URL hystrixUrl = new URL(url + "/actuator/hystrix.stream");
InputStream in = hystrixUrl.openStream();
byte[] buffer = new byte[1024];
in.read(buffer);
String contents = new String(buffer);
assertTrue("Wrong content: \n" + contents, contents.contains("data") || contents.contains("ping"));
in.close();
}
@Test
public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.configure(restTemplate);
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder, "user", "passwd");
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void contextLoads() {
ResponseEntity<Environment> response = new TestRestTemplate().exchange(
"http://localhost:" + this.port + "/foo/development/", HttpMethod.GET,
getV2AcceptEntity(), Environment.class);
Environment environment = response.getBody();
assertThat(environment.getPropertySources().isEmpty()).isFalse();
assertThat(environment.getPropertySources().get(0).getName())
.isEqualTo("overrides");
ConfigServerTestUtils.assertConfigEnabled(environment);
}
@Test
public void shouldRetrieveValuesFromCredhub() {
Environment environment = new TestRestTemplate().getForObject(
"http://localhost:" + this.port + "/myapp/master/default",
Environment.class);
assertThat(environment.getPropertySources().isEmpty()).isFalse();
assertThat(environment.getPropertySources().get(0).getName())
.isEqualTo("credhub-myapp-master-default");
assertThat(environment.getPropertySources().get(0).getSource().toString())
.isEqualTo("{key=value}");
}