Java 如何在Spring引导测试中跳过TestRestTemplate的身份验证?
下面是我的测试课。hello world端点只返回一个包含文本的HTML页面,即hello陌生人Java 如何在Spring引导测试中跳过TestRestTemplate的身份验证?,java,spring-boot,Java,Spring Boot,下面是我的测试课。hello world端点只返回一个包含文本的HTML页面,即hello陌生人 @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HelloWorldTest { @Autowired private HelloWorldController controller;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloWorldTest {
@Autowired
private HelloWorldController controller;
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
private int port;
@Test
public void contextLoads() throws Exception {
assertThat(controller).isNotNull();
}
@Test
public void greetingShouldReturnDefaultMessage() throws Exception {
String baseUrl = "http://localhost:" + port;
assertThat(this.restTemplate.getForObject(baseUrl+"/hello-world", String.class))
.contains("Hello Stranger!");
}
}
这是我的安全配置:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
它只是将所有经过身份验证的用户重定向到登录页面
我已尝试在测试目录中添加@WithMockUser注释或添加另一个安全配置类,以覆盖默认配置。但到目前为止,一切似乎都不起作用
任何关于阅读文档的帮助或建议都将不胜感激 我已经设法解决了这个问题,首先创建了另一个web安全配置,而不需要登录/授权,然后通过在我的测试目录中添加
@Profile
到我的配置类和生产/dev/test
配置文件(即添加“spring.profiles.active=test”
)
不确定这是否是解决此问题的最佳方法,但它目前仍然有效。另一种对我有效的方法是覆盖运行集成测试的正常安全配置,如下所示:
@TestConfiguration
@Order(-101)
@EnableWebSecurity
class TestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity security) throws Exception {
security.httpBasic().and().formLogin().disable();
}
}
可能会有帮助: