【问题标题】:How to create an instance of HttpServletRequest for unit testing?如何创建用于单元测试的 HttpServletRequest 实例?
【发布时间】:2016-09-06 20:20:20
【问题描述】:

在对 SO 进行一些搜索时,我遇到了 this 一段代码,用于从 URL 中提取“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 返回我希望它返回的内容(举个例子,因为模拟本质上会覆盖一些返回固定值的方法),那么我那时并没有真正测试代码。我也尝试了 httpunit 库,但这也无济于事。

【问题讨论】:

  • 您在模拟依赖项,而不是在测试系统。您没有在这里测试 getRequestURL,因为它不在范围内
  • 您可以尝试在 spring-test maven 依赖项中使用 org.springframework.mock.web.MockHttpServletRequest。它可以满足我的需要。

标签: unit-testing servlets


【解决方案1】:

我使用 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 对象才能工作的方法。

【讨论】:

  • 我不认为这会起作用,因为当 getRequestUrl 和 getServletUrl 被调用时,对象会返回什么?如果我模拟这些方法,那么我就不会真正测试它们的实际行为。
  • 你为什么要测试那些,你不相信应用服务器,因为它可能行为不端?如果是这样,您可能需要考虑嵌入类似 jetty 的东西并使用它来运行您的测试,但这会使您的测试变得非常复杂。单元测试应该测试您的代码,如果您不信任该框架,则使用 httpunit 之类的东西构建集成测试,在服务器部署和运行后运行。
  • 一个考虑,在测试中如何调用getAppUrl()方法?我的意思是,你如何实例化HttpServletResponse 类型的参数?因为在测试中你必须调用方法,但我没有得到如何实例化对象。
猜你喜欢
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2021-12-06
相关资源
最近更新 更多