簡體   English   中英

使用jUnit和Spring測試servlet並進行過濾

[英]Test servlet and filter with jUnit and Spring

我想做一些集成測試,以使用jUnit測試servlet上下文(自定義過濾器和servlet)。

場景如下:瀏覽器向服務器發出請求以查找用戶。 首先,將請求轉到AuthenticationFilter。 當請求路徑正確時,請轉到LogginServlet,在其中嘗試找到有關某些用戶的信息,並將其返回給瀏覽器。

我嘗試用MockMvc對其進行測試。 我可以向MockMvc添加過濾器(正確執行),但不能添加servlet,它會在過濾器之后調用。 我嘗試使用不同的方法來使spring管理servlet,但是我無法以正確的方式對其進行配置。

誰能幫助我使此集成測試正常工作? 我只想在這種情況下過濾器和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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM