I want to test following code with easymock. I have created mock socket and mock inputstream but I am not able to mock the read method. Can anyone please help me
byte[] lenbuf = new byte[2];
sock.getInputStream().read(lenbuf);
I am trying following in my unit test
InputStream mockInputStream = createMock(InputStream.class);
expect(mockInputStream.read(new byte[2])).andReturn(2);
replay(mockInputStream);
it gives me following error
Unexpected method call InputStream.read([0, 0]):
InputStream.read([0, 0]): expected: 1, actual: 0
Thanks
(Aside: try (byte[]) EasyMock.anyObject() instead of new byte[2] as the parameter to read.)
Mocking an input stream is a lot of work and not really worth doing. There are many ways to get fake input streams that your tests can set up, without using mock objects. Try this:
String fakeInput = "This is the string that your fake input stream will return";
StringReader reader = new StringReader(fakeInput);
InputStream fakeStream = new ReaderInputStream(reader);
Note that ReaderInputStream is in Apache Commons IO
You can also do it without the Reader, using StringBufferInputStream. This doesn't require Commons IO. It has deficiencies, but it's probably good enough for test code.
In fact, mocking in general is hard work compared to other forms of faking. I do it only when I want to prove that the that innards of my class being tested is doing something in a particular way, and that's not really what tests are for: good tests prove the interfaces work, and allow the implementations to change. Have a read of the eminent Martin Fowler's definition of mocks and Andrew Trenk's take on some of the problems they can introduce.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With