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

Unit testing 如何为单元测试创建HttpServletRequest实例?,unit-testing,servlets,Unit Testing,Servlets,在上进行一些搜索时,我遇到了一段从URL中提取“appUrl”的代码: public static String getAppUrl(HttpServletRequest request) { String requestURL = request.getRequestURL().toString(); String servletPath = request.getServletPath(); return requestURL.substring(0, re

在上进行一些搜索时,我遇到了一段从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库,但也没有用。

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

    .....
公共类TestLogin{
@试验
public void testGetMethod()引发IOException{
//模拟HttpSession并将其插入模拟HttpServletRequest
HttpSession session=mock(HttpSession.class);
给定(session.getId()).willReturn(“sessionid”);
//模拟HttpServletRequest
HttpServletRequest=mock(HttpServletRequest.class);
给定(request.getSession())。将返回(session);
给定(request.getSession(true)).willReturn(session);
HashMap params=新的HashMap();
给定(request.getParameterMap())。将返回(params);
//模拟HttpServletResponse
HttpServletResponse=mock(HttpServletResponse.class);
PrintWriter=mock(PrintWriter.class);
给定(response.getWriter())。将返回(writer);
.....

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

我认为这不起作用,因为当调用getRequestUrl和getServletUrl时,对象会返回什么?如果我模拟这些方法,那么我就不会真正测试它们的实际行为。你为什么要测试它们,你不相信应用程序服务器,因为它可能会出错吗?如果是这样,你可能想考虑嵌入像JETTY之类的东西来运行你的测试,但是这会使你的测试变得非常复杂。单元测试应该测试你的代码,如果你不信任这个框架,那么用部署在服务器部署后运行的HTTPUnit之类的东西来构建集成测试。考虑一下,如何调用方法
getAppUrl()
在测试中?我的意思是,你如何实例化类型为
HttpServletResponse
的参数?因为在测试中你必须调用方法,但我不知道如何实例化对象。你在模拟依赖项,而不是测试中的系统。你没有在这里测试getRequestURL,因为它不在可能的dupl范围内你们中的大多数人可以尝试在
spring测试中使用
org.springframework.mock.web.MockHttpServletRequest
,它满足了我的需要。