gpt4 book ai didi

java - 使用 jUnit 和 Spring 测试 servlet 和过滤器

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:07 44 4
gpt4 key购买 nike

我想使用 jUnit 进行一些集成测试来测试 servlet 上下文(自定义过滤器和 servlet)。

场景如下:浏览器向服务器发出请求以查找用户。首先,请求会想到AuthenticationFilter。当请求路径正确时,然后转到 LogginServlet,我尝试在其中查找有关某些用户的信息并将其返回到浏览器。

我尝试用 MockMvc 来测试它。我可以向 MockMvc 添加过滤器(正确执行),但无法添加 servlet,它会在过滤器之后调用。我尝试了不同的方法来使 servlet 由 spring 管理,但我无法以正确的方式配置它。

任何人都可以帮助我使这个集成测试正常工作吗?我只想在这种情况下过滤器和 servlet 一起工作。

测试代码:

public class MockMvcSecurityIT {

@Autowired
private WebApplicationContext context;

@Before
public void initMocks(){
this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilter(new AuthenticationFilter(), "/*").build();
}

@Test
public void stage10_firstRequestForLoginPageShouldReturnProperPageWithoutCreateingSession () throws Exception {

MvcResult mvcResult = mockMvc.perform(get("/login"))
.andDo(print())
.andExpect(status().isOk()).andReturn();

}

过滤器类别:

@WebFilter(
urlPatterns = "/*",
dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD}
)
public class AuthenticationFilter implements Filter {

@Override
public void init(FilterConfig config) throws ServletException {}

@Override
public void destroy() {}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// business logic to verify request


}
}

Servlet:

@WebServlet(
name = "LoginServlet",
urlPatterns = {"/login"}
)
public class LoginServlet extends HttpServlet {

private AuthenticationProvider authenticationProvider;

public LoginServlet() {}

@Autowired
public LoginServlet(AuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}

@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);

// business logic to find and return user

}

}

最佳答案

我发现 Spring 中的 TestContext 框架在幕后使用 TestDispatcherServlet,并且我无法配置或注册其他 Servlet。有一个问题链接:

https://jira.spring.io/browse/SPR-10199

我需要找到其他方法来测试我的 servlet 上下文。

编辑:

例如,最好的解决方案似乎是 EmbeddedTomcat 和 HttpUnit。

关于java - 使用 jUnit 和 Spring 测试 servlet 和过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49576288/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com