如何在 SpringBootTest 中将基本身份验证添加到 Autowired testRestTemplate; Spring 引导 1.4
How to add basic auth to Autowired testRestTemplate in SpringBootTest; Spring Boot 1.4
我在 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
@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 basic authentication with RestTemplate
我想使用 Autowired testRestTemplate 来避免在我的测试中解析主机和端口。有办法吗?
这在 Spring Boot 1.4.1 中得到了修复,它有一个额外的方法
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"));
}
有更好的解决方案,因此您无需每次都重新输入 withBasicAuth 部分
@Autowired
private TestRestTemplate testRestTemplate;
@BeforeClass
public void setup() {
BasicAuthorizationInterceptor bai = new BasicAuthorizationInterceptor(CLIENT_NAME, CLIENT_PASSWORD);
testRestTemplate.getRestTemplate().getInterceptors().add(bai);
}
@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.postForObject(SyntheticsConstants.OAUTH_ENDPOINT, request, Map.class);
assertNotNull("Wrong response: " + token, token.get("access_token"));
}
虽然 是正确的,但在我的例子中,我不得不在每个测试方法中复制 testRestTemplate.withBasicAuth(...)
和 class.
所以,我尝试在 src/test/java/my.microservice.package
中定义这样的配置:
@Configuration
@Profile("test")
public class MyMicroserviceConfigurationForTest {
@Bean
public TestRestTemplate testRestTemplate(TestRestTemplate testRestTemplate, SecurityProperties securityProperties) {
return testRestTemplate.withBasicAuth(securityProperties.getUser().getName(), securityProperties.getUser().getPassword());
}
}
似乎 具有覆盖默认 TestRestTemplate
定义的效果,允许在我的测试中的任何地方注入凭据感知 TestRestTemplate
classes。
我不完全确定这是否真的是一个有效的解决方案,但您可以试一试...
如果您仍在应用程序中使用基本身份验证,并且在 application.properties 文件中设置 "user.name" 和 "user.password" 属性,我认为有更好的解决方案:
public class YourEndpointClassTest {
private static final Logger logger = LoggerFactory.getLogger(YourEndpointClassTest.class);
private static final String BASE_URL = "/your/base/url";
@TestConfiguration
static class TestRestTemplateAuthenticationConfiguration {
@Value("${spring.security.user.name}")
private String userName;
@Value("${spring.security.user.password}")
private String password;
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder().basicAuthentication(userName, password);
}
}
@Autowired
private TestRestTemplate restTemplate;
//here add your tests...
在单个测试用例中,你可以这样做:
@Test
public void test() {
ResponseEntity<String> entity = testRestTemplate
.withBasicAuth("username", "password")
.postForEntity(xxxx,String.class);
Assert.assertNotNull(entity.getBody());
}
并且对于每个测试用例,在您的测试中添加此方法 class:
@Before
public void before() {
// because .withBasicAuth() creates a new TestRestTemplate with the same
// configuration as the autowired one.
testRestTemplate = testRestTemplate.withBasicAuth("username", "password");
}
我在 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
@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 basic authentication with RestTemplate
我想使用 Autowired testRestTemplate 来避免在我的测试中解析主机和端口。有办法吗?
这在 Spring Boot 1.4.1 中得到了修复,它有一个额外的方法
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"));
}
有更好的解决方案,因此您无需每次都重新输入 withBasicAuth 部分
@Autowired
private TestRestTemplate testRestTemplate;
@BeforeClass
public void setup() {
BasicAuthorizationInterceptor bai = new BasicAuthorizationInterceptor(CLIENT_NAME, CLIENT_PASSWORD);
testRestTemplate.getRestTemplate().getInterceptors().add(bai);
}
@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.postForObject(SyntheticsConstants.OAUTH_ENDPOINT, request, Map.class);
assertNotNull("Wrong response: " + token, token.get("access_token"));
}
虽然 testRestTemplate.withBasicAuth(...)
和 class.
所以,我尝试在 src/test/java/my.microservice.package
中定义这样的配置:
@Configuration
@Profile("test")
public class MyMicroserviceConfigurationForTest {
@Bean
public TestRestTemplate testRestTemplate(TestRestTemplate testRestTemplate, SecurityProperties securityProperties) {
return testRestTemplate.withBasicAuth(securityProperties.getUser().getName(), securityProperties.getUser().getPassword());
}
}
似乎 具有覆盖默认 TestRestTemplate
定义的效果,允许在我的测试中的任何地方注入凭据感知 TestRestTemplate
classes。
我不完全确定这是否真的是一个有效的解决方案,但您可以试一试...
如果您仍在应用程序中使用基本身份验证,并且在 application.properties 文件中设置 "user.name" 和 "user.password" 属性,我认为有更好的解决方案:
public class YourEndpointClassTest {
private static final Logger logger = LoggerFactory.getLogger(YourEndpointClassTest.class);
private static final String BASE_URL = "/your/base/url";
@TestConfiguration
static class TestRestTemplateAuthenticationConfiguration {
@Value("${spring.security.user.name}")
private String userName;
@Value("${spring.security.user.password}")
private String password;
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder().basicAuthentication(userName, password);
}
}
@Autowired
private TestRestTemplate restTemplate;
//here add your tests...
在单个测试用例中,你可以这样做:
@Test
public void test() {
ResponseEntity<String> entity = testRestTemplate
.withBasicAuth("username", "password")
.postForEntity(xxxx,String.class);
Assert.assertNotNull(entity.getBody());
}
并且对于每个测试用例,在您的测试中添加此方法 class:
@Before
public void before() {
// because .withBasicAuth() creates a new TestRestTemplate with the same
// configuration as the autowired one.
testRestTemplate = testRestTemplate.withBasicAuth("username", "password");
}