【发布时间】:2018-12-13 06:07:45
【问题描述】:
这是我的用户控制器:
@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>
过滤器是:
public class ApiAuthenticationFilter extends OncePerRequestFilter {
private final RequestMatcher requestMatcher;
public ApiAuthenticationFilter() {
this.requestMatcher = new OrRequestMatcher(
new AntPathRequestMatcher("/users/**"));
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
if (requestMatcher.matches(request)) {
return true;
}
return super.shouldNotFilter(request);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filterChain.doFilter(request, response);
}
}
我添加配置:
@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/**"))
http://localhost:8080/users/current
这在我的浏览器中完美运行,但测试失败并出现未经授权的异常。这里有什么问题?
【问题讨论】:
标签: spring-boot spring-security spring-test-mvc