EasyMock - 无法模拟HTTPServletRequest输入流

时间:2013-06-07 11:04:25

标签: java junit4 easymock

我正在尝试模拟HTTPServletRequest对象,以便对我服务器中的请求处理程序类进行JUnit测试。 如何使用EasyMock模拟ServletInputStream?我试过了

HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
InputStream is = new ByteArrayInputStream(postDataContent.getBytes());
EasyMock.expect( req.getInputStream()).andReturn((ServletInputStream) is);

但它正在给出例外

java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to javax.servlet.ServletInputStream
 at test.com.comcast.cdvr.handler.ArchivingRequestHandlerTest.testHandlePutRequest(ArchivingRequestHandlerTest.java:76)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)
 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
 at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
 at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

2 个答案:

答案 0 :(得分:0)

ByteArrayInputStream不是ServletInputStream。通过使用演员

EasyMock.expect( req.getInputStream()).andReturn((ServletInputStream) is);

你可以欺骗编译器,但不是我们心爱的JVM :-)。您需要实现ServletInputStream的正确实现,或者使用众多Web测试库中的一个。

祝你好运!

<强>更新

模拟ServletInputStream时发生的异常是由EasyMock所需的缺失依赖引起的。来自EasyMock documentation page

  

cglib(2.2)和Objenesis(1.2)必须在类路径中才能执行类模拟

答案 1 :(得分:0)

您可以像模仿HttpServletRequest

一样嘲笑它
ServletInputStream mockInputStream = EasyMock.createMock(ServletInputStream.class);
EasyMock.expect(req.getInputStream()).andReturn(mockInputStream);