简体   繁体   中英

How to create a inputStream with test data

I am trying write a unit test. In the class I am testing, I am passing a java.net.Socket object through the constructor. The variable of this is called connection . In that class, there is a line:

ObjectInputStream in = new ObjectInputStream(connection.getInputStream());

Now in my unit test I am passing a mocked Socket object when creating an instance of that class. In my unit test I am writing the following:

when(socket.getInputStream()).thenReturn(getInputStream());

   private InputStream getInputStream() throws IOException
   {
       InputStream d = new ReaderInputStream(new StringReader("test data"));
      ObjectInputStream o = new ObjectInputStream(d);
      return d;
   }

but when running that, i get the following error:

java.io.StreamCorruptedException: invalid stream header: 64666466

at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:783)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:278)

Not sure how to overcome this. The error is stemming from ObjectInputStream o = new ObjectInputStream(d);

ObjectInputStream validates header by checking input stream. In you are case, you are streaming data which supported by ObjectInputStream.

So, you have to use stream which can be understandable by ObjectInputStream ie generated input data from ObjectOutputStream.

Here is one sample example;

final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeUTF("Hello World");

    InputStream d = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    ObjectInputStream o = new ObjectInputStream(d);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM