0

我正在尝试模拟 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)
4

2 回答 2

0

AByteArrayInputStream不是ServletInputStream. 通过使用演员表

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

你可以愚弄编译器,但不能愚弄我们心爱的 JVM :-)。您需要正确实现ServletInputStream或使用众多 Web 测试库之一。

祝你好运!

更新:

模拟 ServletInputStream 时发生的异常是由于缺少 EasyMock 所需的依赖项引起的。从EasyMock 文档页面

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

于 2013-06-07T11:13:17.910 回答
0

你可以用你模拟的方式来模拟它HttpServletRequest

ServletInputStream mockInputStream = EasyMock.createMock(ServletInputStream.class);
EasyMock.expect(req.getInputStream()).andReturn(mockInputStream);
于 2013-06-07T11:13:45.117 回答