[英]How to skip authentication for TestRestTemplate in Spring Boot Tests?
下面是我的測試課。 hello-world 端點僅返回一個包含文本的 HTML 頁面,即 Hello Stranger!
@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 安全配置,然后通過我的測試目錄中的application.properties
添加@Profile
到我的配置類和production/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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.