MockMvc WebFilter不生效问题解决

在SpringBoot项目中,配置了一个@WebFilter,正常启动没问题,但是通过MockMvc进行单元测试死活不生效

1
2
3
4
5
6
7
8
9
10
11
@Configuration
@Order(1)
@WebFilter(urlPatterns = ["/**"])
class HttpServletRequestWrapperFilter : Filter {
override fun doFilter(req: ServletRequest?, resp: ServletResponse?, chain: FilterChain?) {
when (req) {
is HttpServletRequest -> chain?.doFilter(MyHttpServletRequestWrapper(req), resp)
else -> chain?.doFilter(req, resp)
}
}
}

后来搞了半天,原来在构建MockMvc对象时,需要手动添加过滤器,这坑爹的玩意儿。

1
2
3
4
5
6
@Before
fun setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilters<DefaultMockMvcBuilder>(HttpServletRequestWrapperFilter())
.build()
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×