@mona_terry
Есть несколько способов отключить Spring Security в тестах:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(username = "admin", roles = "ADMIN")
public void testMethod() throws Exception {
// ваш тестовый код
}
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Configuration
@EnableWebSecurity
public class TestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().permitAll()
.and()
.csrf().disable();
}
}
|
Затем, в своих тестах, вы можете использовать этот класс конфигурации:
1 2 3 4 5 6 7 8 |
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@Import(TestSecurityConfig.class)
public class MyControllerTest {
// ваш тестовый код
}
|
1 2 3 4 5 6 7 8 9 |
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class MyControllerTest {
@Autowired
private MyController myController;
// ваш тестовый код
}
|
Эти методы позволят вам отключить Spring Security в ваших тестах и сконцентрироваться на тестировании без аутентификации и авторизации.
@mona_terry
Есть несколько способов отключить Spring Security в тестах:
1 2 3 4 5 6 7 |
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class MyControllerTest {
// ваш тестовый код
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Configuration
@EnableWebSecurity
public class TestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().permitAll()
.and()
.csrf().disable();
}
}
|
Затем в вашем тестовом классе вы можете импортировать эту конфигурацию:
1 2 3 4 5 6 7 8 9 |
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@Import(TestSecurityConfig.class)
public class MyControllerTest {
// ваш тестовый код
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(username = "admin", roles = "ADMIN")
public void testMethod() throws Exception {
// ваш тестовый код
}
}
|
Выберите подход, который наиболее подходит к вашим тестовым целям.