Bla*_*man 31 java junit easymock
我有一个查找查询参数并返回布尔值的函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
我的pom.xml中有junit和easymock,如何模拟HttpServletRequest?
Yog*_*ngh 19
使用一些模拟框架,例如Mockito或JMock,它具有此类对象的模拟能力.
在Mockito,你可以做嘲笑:
HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
Run Code Online (Sandbox Code Playgroud)
有关Mockito的详细信息,请参阅:我如何饮用?在Mockito网站上.
在JMock中,你可以做模拟:
Mockery context = new Mockery();
HttpServletRequest mockedRequest = context.mock(HttpServletRequest.class);
Run Code Online (Sandbox Code Playgroud)
有关jMock的详细信息,请参阅:jMock - 入门
Gui*_*one 12
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");
}
}
Run Code Online (Sandbox Code Playgroud)
Fog*_*Day 11
这是一个老线程......但问题仍然是相关的.
另一个不错的选择是Spring框架中的MockServiceRequest和MockServiceResponse:
http://docs.spring.io/spring/docs/2.0.x/api/org/springframework/mock/web/package-summary.html
归档时间: |
|
查看次数: |
79321 次 |
最近记录: |