【发布时间】:2018-09-09 14:31:17
【问题描述】:
我想进行一些集成测试,以使用 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
}
}
小服务程序:
@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
}
}
【问题讨论】:
标签: java spring servlets model-view-controller integration-testing