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

mor*_*eus 3 unit-testing servlets

在对 SO 进行一些搜索时,我遇到了这段代码以从 URL 中提取“appUrl”:

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

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

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

Ale*_*exC 7

我使用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);

    .....
Run Code Online (Sandbox Code Playgroud)

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