我在 Spring Boot 1.4 之前的 OAuth 集成测试如下(更新只是为了不使用已弃用的功能):
@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"));
}
}
我现在想使用 Autowired TestRestTemplate,如此处所述http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-working-with-random-ports 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"));
}
}
我认为这是添加身份验证的最接近的方法:
Spring 4.0.0 使用 RestTemplate 进行基本身份验证 https://stackoverflow.com/questions/21998405/spring-4-0-0-basic-authentication-with-resttemplate
我想使用 Autowired testRestTemplate 来避免在测试中解析主机和端口。有没有办法做到这一点?