【问题标题】:Spring Boot OncePerRequestFilter shouldNotFilter JunitSpring 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

【问题讨论】:

    标签: java spring spring-mvc spring-boot junit


    【解决方案1】:

    /healthrequest.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 为真的初始化。
    猜你喜欢
    • 2020-11-18
    • 2019-11-19
    • 2021-07-18
    • 2023-04-02
    • 2019-10-26
    • 2018-03-09
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    相关资源
    最近更新 更多