【发布时间】: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