【问题标题】:Spring boot unit test mvc with spring security带有spring security的Spring Boot单元测试mvc
【发布时间】: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


    【解决方案1】:

    我认为 SecurityConfigApiAuthenticationFilter 在开始测试时没有加载到上下文中。

    尝试添加:

     @SpringBootTest(classes =  { Application.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    

    这里,Application 类是加载配置的主类。

    编辑 1

    其他way 似乎很有趣。

    【讨论】:

      猜你喜欢
      • 2017-10-21
      • 2019-01-20
      • 1970-01-01
      • 2018-02-05
      • 2016-05-28
      • 2018-01-02
      • 2012-06-15
      • 2020-09-18
      相关资源
      最近更新 更多