我想用 easymock 测试下面的代码。我已经创建了模拟套接字和模拟输入流,但我无法模拟读取方法。谁能帮帮我
byte[] lenbuf = new byte[2];
sock.getInputStream().read(lenbuf);
我在单元测试中尝试跟随
InputStream mockInputStream = createMock(InputStream.class);
expect(mockInputStream.read(new byte[2])).andReturn(2);
replay(mockInputStream);
它给了我以下错误
Unexpected method call InputStream.read([0, 0]):
InputStream.read([0, 0]): expected: 1, actual: 0
谢谢
最佳答案
(另外:尝试使用 (byte[]) EasyMock.anyObject()
而不是 new byte[2]
作为要读取的参数。)
模拟输入流是一项繁重的工作,不值得去做。有很多方法可以在不使用模拟对象的情况下获取测试可以设置的假输入流。试试这个:
String fakeInput = "This is the string that your fake input stream will return";
StringReader reader = new StringReader(fakeInput);
InputStream fakeStream = new ReaderInputStream(reader);
请注意 ReaderInputStream 在 Apache Commons IO 中
您也可以在没有 Reader 的情况下使用 StringBufferInputStream 来完成。这不需要 Commons IO。它有不足之处,但对于测试代码来说可能已经足够好了。
事实上,与其他形式的伪造相比,一般来说,模拟是一项艰巨的工作。只有当我想证明我的被测试类的内部正在以特定方式做某事时,我才会这样做,而这并不是测试的真正目的:好的测试证明接口(interface)有效,并允许实现改变。阅读著名的 Martin Fowler 的 definition of mocks Andrew Trenk 对 some of the problems they can introduce 的看法.
关于java - Easymock 模拟输入流读取操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22060889/