Issue
My OAuth integration test before Spring Boot 1.4 looked as follows(updates just to not use deprecated features):
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ApplicationConfiguration.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
public class OAuth2IntegrationTest {
@Value("${local.server.port}")
private int port;
private static final String CLIENT_NAME = "client";
private static final String CLIENT_PASSWORD = "123456";
@Test
public void testOAuthAccessTokenIsReturned() {
MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
request.set("username", "user");
request.set("password", password);
request.set("grant_type", "password");
@SuppressWarnings("unchecked")
Map<String, Object> token = new TestRestTemplate(CLIENT_NAME, CLIENT_PASSWORD)
.postForObject("http://localhost:" + port + "/oauth/token", request, Map.class);
assertNotNull("Wrong response: " + token, token.get("access_token"));
}
}
I now want to use Autowired TestRestTemplate as stated here http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-working-with-random-ports
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
ApplicationConfiguration.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class OAuth2IntegrationTest {
private static final String CLIENT_NAME = "client";
private static final String CLIENT_PASSWORD = "123456";
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void testOAuthAccessTokenIsReturned() {
MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
request.set("username", "user");
request.set("password", password);
request.set("grant_type", "password");
@SuppressWarnings("unchecked")
Map<String, Object> token1 = this.testRestTemplate. //how to add basic auth here
assertNotNull("Wrong response: " + token, token.get("access_token"));
}
}
I saw this as the closest way to add auth:
I want to use the Autowired testRestTemplate to avoid resolving host and ports in my test. Is there a way to do this?
Solution
This got fixed in Spring Boot 1.4.1 which has an additional method
testRestTemplate.withBasicAuth(USERNAME,PASSWORD)
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void testOAuthAccessTokenIsReturned() {
MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
request.set("username", USERNAME);
request.set("password", password);
request.set("grant_type", "password");
@SuppressWarnings("unchecked")
Map<String, Object> token = this.testRestTemplate.withBasicAuth(CLIENT_NAME, CLIENT_PASSWORD)
.postForObject(SyntheticsConstants.OAUTH_ENDPOINT, request, Map.class);
assertNotNull("Wrong response: " + token, token.get("access_token"));
}
Answered By - Tuhin Kanti Sharma