如何模拟HttpServletRequest?

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

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.xml中有junit和easymock,如何模拟HttpServletRequest?

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

以下是如何对getBooleanFromRequest方法进行unit testing的示例

 // 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"); } } 

使用一些模拟框架,例如MockitoJMock ,它具有这些对象的模拟能力。

在Mockito中,你可以做嘲笑:

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

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

在JMock中,你可以做模拟:

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

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

这是一个老线程……但问题仍然存在。

另一个不错的选择是Spring框架中的MockServiceRequest和MockServiceResponse:

http://docs.spring.io/spring/docs/2.0.x/api/org/springframework/mock/web/package-summary.html

我不知道easymock,但Johannes Link撰写的“Java中的unit testing:如何测试驱动代码”这本书包含了如何使用他构建虚拟对象的库测试Servlet的解释。

这本书的配套网站现在已经不见了(出版公司改变了一些东西……)但是原始德国出版物的配套网站仍然存在 。 从中, 您可以下载所有虚拟对象的定义 。

看看Mockrunner: http ://mockrunner.sourceforge.net/

它有很多易于使用的Java EE模拟,包括HttpServletRequest和HttpServletResponse。