如何嘲笑 HttpServletRequest?

2022-09-01 04:33:57

我有一个函数,它查找查询参数并返回一个布尔值:

  public static Boolean getBooleanFromRequest(HttpServletRequest request, String key) {
        Boolean keyValue = false;
        if(request.getParameter(key) != null) {
            String value = request.getParameter(key);
            if(keyValue == null) {
                keyValue = false;
            }
            else {
                if(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("1")) {
                    keyValue = true;
                }
            }
        }
        return keyValue;
    }

我的pom中既有junit又有easymock.xml,我该如何去嘲笑HttpServletRequest?


答案 1

使用一些模拟框架,例如MockitoJMock,它们带有此类对象的模拟能力。

在Mockito中,您可以按如下方式进行模拟:

 HttpServletRequest  mockedRequest = Mockito.mock(HttpServletRequest.class);

有关Mockito的详细信息,请参阅Mockito网站上的:我如何饮用它?

在JMock中,你可以做嘲笑:

 Mockery context = new Mockery();
 HttpServletRequest  mockedRequest = context.mock(HttpServletRequest.class);

有关 jMock 的详细信息,请参阅:jMock - 入门


答案 2

HttpServletRequest与任何其他界面非常相似,因此您可以通过遵循EasyMock自述文件来模拟它

下面是如何单元测试 getBooleanFromRequest 方法的示例

// static import allows for more concise code (createMock etc.)
import static org.easymock.EasyMock.*;

// other imports omitted

public class MyServletMock
{
   @Test
   public void test1()
   {
      // Step 1 - create the mock object
      HttpServletRequest req = createMock(HttpServletRequest.class);

      // Step 2 - record the expected behavior

      // to test true, expect to be called with "param1" and if so return true
      // Note that the method under test calls getParameter twice (really
      // necessary?) so we must relax the restriction and program the mock
      // to allow this call either once or twice
      expect(req.getParameter("param1")).andReturn("true").times(1, 2);

      // program the mock to return false for param2
      expect(req.getParameter("param2")).andReturn("false").times(1, 2);

      // switch the mock to replay state
      replay(req);

      // now run the test.  The method will call getParameter twice
      Boolean bool1 = getBooleanFromRequest(req, "param1");
      assertTrue(bool1);
      Boolean bool2 = getBooleanFromRequest(req, "param2");
      assertFalse(bool2);

      // call one more time to watch test fail, just to liven things up
      // call was not programmed in the record phase so test blows up
      getBooleanFromRequest(req, "bogus");

   }
}

推荐