Try to search your question here, if you can't find : Ask Any Question Now ?

How to add basic auth to Autowired testRestTemplate in SpringBootTest; Spring Boot 1.4

HomeCategory: stackoverflowHow to add basic auth to Autowired testRestTemplate in SpringBootTest; Spring Boot 1.4
Avatarsourav asked 2 years ago

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:

Spring 4.0.0 basic authentication with RestTemplate

I want to use the Autowired testRestTemplate to avoid resolving host and ports in my test. Is there a way to do this?

1 Answers
Best Answer
AvatarArben answered 2 years ago
Your Answer

5 + 12 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com