org.springframework.boot.test.web.client.TestRestTemplate Java Examples

The following examples show how to use org.springframework.boot.test.web.client.TestRestTemplate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: X509ApplicationTests.java    From building-microservices with Apache License 2.0 8 votes vote down vote up
@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");
}
 
Example #2
Source File: GrantByResourceOwnerPasswordCredentialTest.java    From demo-spring-boot-security-oauth2 with MIT License 6 votes vote down vote up
@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));
}
 
Example #3
Source File: GrantByResourceOwnerPasswordCredentialTest.java    From demo-spring-boot-security-oauth2 with MIT License 6 votes vote down vote up
@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));
}
 
Example #4
Source File: GrantByImplicitProviderTest.java    From demo-spring-boot-security-oauth2 with MIT License 6 votes vote down vote up
@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());
}
 
Example #5
Source File: MVCJettyITest.java    From java-spring-web with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #6
Source File: ApplicationDashboardPathTests.java    From didi-eureka-server with MIT License 6 votes vote down vote up
@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"));
}
 
Example #7
Source File: TraceSampleApplicationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example #8
Source File: CompositeIntegrationTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #9
Source File: ApplicationServletPathTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void catalogLoads() {
	@SuppressWarnings("rawtypes")
	ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
			"http://localhost:" + this.port + "/servlet/eureka/apps", Map.class);
	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
 
Example #10
Source File: ApplicationContextTests.java    From didi-eureka-server with MIT License 5 votes vote down vote up
@Test
public void cssAvailable() {
	ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
			"http://localhost:" + this.port + "/context/eureka/css/wro.css",
			String.class);
	assertEquals(HttpStatus.OK, entity.getStatusCode());
}
 
Example #11
Source File: ApplicationServletPathTests.java    From didi-eureka-server with MIT License 5 votes vote down vote up
@Test
public void catalogLoads() {
	@SuppressWarnings("rawtypes")
	ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
			"http://localhost:" + this.port + "/eureka/apps", Map.class);
	assertEquals(HttpStatus.OK, entity.getStatusCode());
}
 
Example #12
Source File: ApplicationServletPathTests.java    From didi-eureka-server with MIT License 5 votes vote down vote up
@Test
public void dashboardLoads() {
	ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
			"http://localhost:" + this.port + "/servlet/", 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>"));
}
 
Example #13
Source File: FunctionEndpointInitializerTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleFunctionMapping() 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"), "stressed", String.class);
	assertThat(response.getBody()).isEqualTo("STRESSED");
	response = testRestTemplate.postForEntity(new URI("http://localhost:" + port + "/reverse"), "stressed", String.class);
	assertThat(response.getBody()).isEqualTo("desserts");
}
 
Example #14
Source File: SpannerRepositoryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestEndpoint() {
	this.spannerRepositoryExample.runExample();

	TestRestTemplate testRestTemplate = new TestRestTemplate();
	ResponseEntity<PagedModel<Trade>> tradesResponse = testRestTemplate.exchange(
			String.format("http://localhost:%s/trades/", this.port),
			HttpMethod.GET,
			null,
			new ParameterizedTypeReference<PagedModel<Trade>>() {
			});
	assertThat(tradesResponse.getBody().getMetadata().getTotalElements()).isEqualTo(8);
}
 
Example #15
Source File: BasicAuthConfigurationIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenCorrectCredentials_whenLogin_ThenSuccess() throws IllegalStateException, IOException {
	restTemplate = new TestRestTemplate();
	User user = new User();
	user.setUserName("user");
	user.setPassword("password");
    ResponseEntity<String> response = restTemplate.postForEntity(base.toString()+"/login",user, String.class);

    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertTrue(response
      .getBody()
      .contains("true"));
}
 
Example #16
Source File: BasicHttpsSecurityApplicationTests.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #17
Source File: RefreshEndpointIntegrationTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void webAccess() throws Exception {
	TestRestTemplate template = new TestRestTemplate();
	template.exchange(
			getUrlEncodedEntity("http://localhost:" + this.port + BASE_PATH + "/env",
					"message", "Hello Dave!"),
			String.class);
	template.postForObject("http://localhost:" + this.port + BASE_PATH + "/refresh",
			null, String.class);
	String message = template.getForObject("http://localhost:" + this.port + "/",
			String.class);
	then(message).isEqualTo("Hello Dave!");
}
 
Example #18
Source File: SampleCompiledConsumerTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void print() {
	assertThat(new TestRestTemplate().postForObject(
		"http://localhost:" + this.port + "/test", "it works", String.class))
		.isNull();
	assertThat(Reference.instance).isEqualTo("it works");
}
 
Example #19
Source File: BasicAuthConfigurationIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenWrongCredentials_whenLogin_ThenReturnFalse() throws IllegalStateException, IOException {
	restTemplate = new TestRestTemplate();
	User user = new User();
	user.setUserName("user");
	user.setPassword("wrongpassword");
    ResponseEntity<String> response = restTemplate.postForEntity(base.toString()+"/login",user, String.class);

    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertTrue(response
      .getBody()
      .contains("false"));
}
 
Example #20
Source File: TestRestTemplateBasicLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() {
    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
    restTemplateBuilder.configure(restTemplate);
    TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
    ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
 
Example #21
Source File: ApplicationContextTests.java    From didi-eureka-server with MIT License 5 votes vote down vote up
@Test
public void jsAvailable() {
	ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
			"http://localhost:" + this.port + "/context/eureka/js/wro.js",
			String.class);
	assertEquals(HttpStatus.OK, entity.getStatusCode());
}
 
Example #22
Source File: CredhubConfigServerIntegrationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@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}");
}
 
Example #23
Source File: ApplicationTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void catalogLoads() {
	@SuppressWarnings("rawtypes")
	ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
			"http://localhost:" + this.port + "/eureka/apps", Map.class);
	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
 
Example #24
Source File: TestRestTemplateBasicLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() {
    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
    restTemplateBuilder.build();
    TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
    ResponseEntity<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
 
Example #25
Source File: RentACarTests.java    From sc-contract-car-rental with Apache License 2.0 5 votes vote down vote up
@Test
public void should_fail_to_reach_fraud() {
	// This will fail
	try {
		ResponseEntity<String> entity = new TestRestTemplate().exchange(RequestEntity
				.get(URI.create("http://localhost:6544/fraud")).build(), String.class);
		BDDAssertions.fail("should fail");
	} catch (ResourceAccessException e) {

	}
	//BDDAssertions.then(entity.getStatusCode().value()).isEqualTo(201);
	//BDDAssertions.then(entity.getBody()).isEqualTo("[\"marcin\",\"josh\"]");
}
 
Example #26
Source File: FunctionEndpointInitializerTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetWithtSupplier() throws Exception {
	FunctionalSpringApplication.run(ApplicationConfiguration.class);
	TestRestTemplate testRestTemplate = new TestRestTemplate();
	String port = System.getProperty("server.port");
	Thread.sleep(200);
	ResponseEntity<String> response = testRestTemplate
			.getForEntity(new URI("http://localhost:" + port + "/supplier"), String.class);
	assertThat(response.getBody()).isEqualTo("Jim Lahey");
}
 
Example #27
Source File: OtherTest.java    From demo-spring-boot-security-oauth2 with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	try {
		String access_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsic3ByaW5nLWJvb3QtYXBwbGljYXRpb24iXSwidXNlcl9uYW1lIjoiYXBwX2NsaWVudCIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJleHAiOjE0OTA5NTI5NzcsImF1dGhvcml0aWVzIjpbIlJPTEVfVVNFUiJdLCJqdGkiOiJmOTA4Njk5Mi1mNTc5LTQzZmEtODBjYi00MmViOTEzMjJmMTkiLCJjbGllbnRfaWQiOiJub3JtYWwtYXBwIn0.dTXMB_yDMEQ5n5fS9VXKjvPDOMJQIFJwbpP7WQdw4WU";
		HttpHeaders headers = new HttpHeaders();
		headers.add("Authorization", "Bearer " + access_token);
		ResponseEntity<String> response = new TestRestTemplate().exchange("http://localhost:" + 8080 + "/resources/roles", HttpMethod.GET,
				new HttpEntity<>(null, headers), String.class);
		System.out.println(response.getBody());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #28
Source File: GrantByClientCredentialTest.java    From demo-spring-boot-security-oauth2 with MIT License 5 votes vote down vote up
@Test
public void accessProtectedResourceByJwtToken() throws JsonParseException, JsonMappingException, IOException, InvalidJwtException {
    ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/client", String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

    response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", 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);

    JwtContext jwtContext = jwtConsumer.process(accessToken);
    logJWTClaims(jwtContext);

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("trusted-app", response.getBody());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/trusted_client", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("[{\"authority\":\"ROLE_TRUSTED_CLIENT\"}]", response.getBody());

}
 
Example #29
Source File: ConfigClientBackwardsCompatibilityIntegrationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackwardsCompatibleFormat() {
	Map environment = new TestRestTemplate().getForObject(
			"http://localhost:" + this.port + "/foo/development/", Map.class);
	Object value = getPropertySourceValue(environment);
	assertThat(value).isInstanceOf(String.class).isEqualTo("true");
}
 
Example #30
Source File: TestRestTemplateBasicLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@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));
}