Spring boot 带Spring security的Spring引导单元测试mvc
这是我的用户控制器:Spring boot 带Spring security的Spring引导单元测试mvc,spring-boot,spring-security,spring-test-mvc,Spring Boot,Spring Security,Spring Test Mvc,这是我的用户控制器: @RestController @RequestMapping(value = "/users") public class UserController { @Autowired private UserService userService; @GetMapping(value = "/current") public User getUser(){ return userService.getCurrentUser(
@RestController
@RequestMapping(value = "/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/current")
public User getUser(){
return userService.getCurrentUser();
}
}
下面是测试控制器中其余端点的测试
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private UserService userService;
@Test
public void getUser() throws Exception {
when(userService.getCurrentUser()).thenReturn(new User("Name", "LastName"));
mvc.perform(get("http://localhost:8080/users/current")).andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.response.firstName").value("Name"))
.andExpect(jsonPath("$.response.lastName").value("LastName"));
}
}
这项测试很有效。之后,我添加了springSecurity:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
我添加了配置:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
ApiAuthenticationFilter authenticationFilter = new ApiAuthenticationFilter();
http.addFilterBefore(authenticationFilter, BasicAuthenticationFilter.class).csrf().disable();
}
}
但现在测试不起作用:
java.lang.AssertionError: Status
Expected :200
Actual :401
但是我设置了AntPathRequestMatcher(“/users/**”)
这在我的浏览器中非常有效,但测试失败,出现未经授权的异常。这里出了什么问题?我认为启动测试时未将
SecurityConfig
和apauthenticationfilter
加载到上下文中
尝试添加:
@SpringBootTest(classes = { Application.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
在这里,Application
class是加载配置的主类
编辑1
其他的似乎很有趣
http://localhost:8080/users/current
@SpringBootTest(classes = { Application.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)