如何为单元测试创​​建HttpServletRequest实例?

时间:2016-09-06 20:20:20

标签: unit-testing servlets

在对SO进行一些搜索时,我遇到了this段代码,用于从网址中提取“appUrl”:

public static String getAppUrl(HttpServletRequest request)
{
     String requestURL = request.getRequestURL().toString();
      String servletPath = request.getServletPath();
      return requestURL.substring(0, requestURL.indexOf(servletPath));
}

我的问题是一个单位如何测试这样的东西?关键问题是如何为单元测试创​​建HttpServletRequest的实例?

Fwiw我尝试了一些谷歌搜索,大多数回复都围绕着嘲笑课堂。但是,如果我模拟类,以便getRequestURL返回我想要它返回的内容(举一个例子,因为mocking基本上覆盖了一些返回固定值的方法),那么我当时并没有真正测试代码。我也尝试了httpunit库,但这也无济于事。

1 个答案:

答案 0 :(得分:3)

我使用 mockito ,这是我用来模拟它的测试方法中的代码块:

public class TestLogin {
@Test
public void testGetMethod() throws IOException {
    // Mock up HttpSession and insert it into mocked up HttpServletRequest
    HttpSession session = mock(HttpSession.class);
    given(session.getId()).willReturn("sessionid");

    // Mock up HttpServletRequest
    HttpServletRequest request = mock(HttpServletRequest.class);
    given(request.getSession()).willReturn(session);
    given(request.getSession(true)).willReturn(session);
    HashMap<String,String[]> params = new HashMap<>();
    given(request.getParameterMap()).willReturn(params);

    // Mock up HttpServletResponse
    HttpServletResponse response = mock(HttpServletResponse.class);
    PrintWriter writer = mock(PrintWriter.class);
    given(response.getWriter()).willReturn(writer);

    .....

希望有帮助,我用它来测试需要servlet对象工作的方法。