Spring Boot OncePerRequestFilter shouldNotFilter Junit
Posted
技术标签:
【中文标题】Spring Boot OncePerRequestFilter shouldNotFilter Junit【英文标题】: 【发布时间】:2019-03-24 22:41:20 【问题描述】:我正在尝试为我的 Spring Boot OncePerRequestFilter shouldNotFilter 方法逻辑添加 junit 测试用例。该逻辑适用于实时 REST 调用,但 junit 案例失败。有什么想法吗?。
这是测试代码。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringFilterTest
@Test
public void getHealthTest() throws Exception
standaloneSetup(new PersonController()).addFilter(new SkipFilter()).build().perform(get("/health")).andExpect(status().isOk());
@Test
public void getPersonTest() throws Exception
standaloneSetup(new PersonController()).addFilter(new SkipFilter()).build().perform(get("/person")).andExpect(status().isAccepted());
private class SkipFilter extends OncePerRequestFilter
private Set<String> skipUrls = new HashSet<>(Arrays.asList("/health"));
private AntPathMatcher pathMatcher = new AntPathMatcher();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException
filterChain.doFilter(request, response);
response.setStatus(HttpStatus.ACCEPTED.value());
@Override
protected boolean shouldNotFilter(HttpServletRequest request)
return skipUrls.stream().anyMatch(p -> pathMatcher.match(p, request.getServletPath()));
@RestController
@RequestMapping(value = "/")
private static class PersonController
@GetMapping("person")
public void getPerson()
@GetMapping("health")
public void getHealth()
我希望 junit @Test 两个案例都能成功,但健康一个总是失败(它使用过滤器)。
Incase,如果你想复制下面是完整的 repo 代码。 https://github.com/imran9m/spring-filter-test
【问题讨论】:
【参考方案1】:当/health
request.getServletPath()
时,下面的表达式计算为假
skipUrls.stream().anyMatch(p -> pathMatcher.match(p, request.getServletPath()));
更改为request.getRequestURI()
以获取uri 和以下条件匹配路径
skipUrls.stream().anyMatch(p -> pathMatcher.match(p, request.getRequestURI()));
【讨论】:
谢谢。在那之后它起作用了。奇怪的是 getServletPath 仅适用于junit。我可能错过了一些使 getServletPath 为真的初始化。以上是关于Spring Boot OncePerRequestFilter shouldNotFilter Junit的主要内容,如果未能解决你的问题,请参考以下文章
为啥 Spring Boot 应用程序 pom 同时需要 spring-boot-starter-parent 和 spring-boot-starter-web?
《02.Spring Boot连载:Spring Boot实战.Spring Boot核心原理剖析》