isA*_*Don 4 spring spring-test spring-test-mvc
我正在尝试运行基本的 MVC 测试
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
Run Code Online (Sandbox Code Playgroud)
但是,这将始终导致java.lang.IllegalArgumentException: Header value must not be null
我发现如果我停用 CORS 过滤器,测试将正常运行而不会出错。
我的 SimpleCORSFilter
@Component
public class SimpleCORSFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
public SimpleCORSFilter() {
log.info("SimpleCORSFilter init");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
//...
chain.doFilter(req, res);
}
}
Run Code Online (Sandbox Code Playgroud)
我的安全配置的一部分
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImp userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new SimpleCORSFilter(),UsernamePasswordAuthenticationFilter.class);
}
}
Run Code Online (Sandbox Code Playgroud)
只有当我删除 SimpleCORSFilter 中的 @Component 并删除.addFilterBefore(new SimpleCORS...)SecurityConfig中的行时,测试才有效。
如何在我的测试中使用 mockMVC?我如何为测试禁用 CORSFilter,或者如何正确地在 mockMvc 中发出请求,以便它不会抛出关于“标头值不能为空”的错误。
我曾尝试在 mockMvc 中设置一个随机标头值,但这并没有改变错误。
java.lang.IllegalArgumentException: Header value must not be null.so 使用 .header(key,value) 传递标头值,如下所示:
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/").header("Origin","*")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5000 次 |
| 最近记录: |