我正在尝试为我的Spring Boot OncePerRequestFilter shouldNotFilter方法逻辑添加junit测试用例。该逻辑在实时REST调用中运行良好,但junit case失败了。有什么想法吗?。
下面是测试代码。
@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@测试用例都能成功,但health-one总是失败(它使用过滤器)。
在这种情况下,如果你想复制下面是完整的回购代码。 https://github.com/imran9m/spring-filter-test
以下表达式的计算结果为false,带 request.getServletPath() 什么时候 /health
request.getServletPath()
/health
skipUrls.stream().anyMatch(p -> pathMatcher.match(p, request.getServletPath()));
更改为 request.getRequestURI()
request.getRequestURI()
skipUrls.stream().anyMatch(p -> pathMatcher.match(p, request.getRequestURI()));