在集成测试中使用 TestRestTemplate 测试 OncePerRequestFilter
我的 OncePerRequestFilter 类结构如下:
@Component
Class FilterA extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain){
Obj A = externalService1();
Obj B = externalService2();
req.setAttribute("attr1", A);
req.setAttribute("attr2", B);
chain.doFilter(req,res);
}
}
我想编写一个集成测试,它将启动应用程序上下文并允许我再次向正在运行的服务器提交 http 请求。为此,我使用了如下所示的 TestRestTemplate
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestA {
@Test
public void testResponse(){
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorisation" : "sdsfsfsfsfsd");
ResponseEntity<String> entity = new TestRestTemplate().exchange(
"http://localhost:" + port + "/endpoint/", HttpMethod.GET , new HttpEntity<Object>(headers), String.class);
}
我的问题是,这直接到达控制器并完全跳过过滤器。有没有办法强制执行 TestRestTemplate 中上面的过滤器类?
My OncePerRequestFilter class structure is as follows :
@Component
Class FilterA extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain){
Obj A = externalService1();
Obj B = externalService2();
req.setAttribute("attr1", A);
req.setAttribute("attr2", B);
chain.doFilter(req,res);
}
}
I want to write an integration test that will spin up the application context and allow me to submit a http request again the running server. For this purpose I used TestRestTemplate like below
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestA {
@Test
public void testResponse(){
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorisation" : "sdsfsfsfsfsd");
ResponseEntity<String> entity = new TestRestTemplate().exchange(
"http://localhost:" + port + "/endpoint/", HttpMethod.GET , new HttpEntity<Object>(headers), String.class);
}
My problem is that this directly reaches the controller and skips the Filter altogether. Is there a way to force the execution of the filter class above in the TestRestTemplate?.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论