Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing outputstream.write(<String>) without creating a file

I am testing a output stream in java something like below.

    Writer outputStream = getOutputStream(fileName);
    if(outputStream != null) {
        try {
            outputStream.write(inputText);
        }
        finally {
            outputStream.close();
        }
    }
    else {
        throw new IOException("Output stream is null");
    }

I am write a mockito test as below

public void testFileWrite() throws IOException {
    when(testObj.getOutputStream(outputFileNameValidValue)).thenReturn(outputStreamMock);
    doNothing().when(outputStreamMock).write(Matchers.anyString());
    doNothing().when(bufferedReaderMock).close();

    testObj.write(outputFileNameValidValue, reveredFileInput);

    verify(outputStreamMock).write(Matchers.anyString());
    verify(outputStreamMock).close();
}

The problem is when you create OutputStreamWriter(new FileOutputStream(filename)) a physical file on the disk is created.

Can we test Outputstream.write without actually writing a file on the disk?

Thanks Anand

like image 200
Anand Avatar asked Feb 17 '12 12:02

Anand


People also ask

How do you write OutputStream to string?

Example: Convert OutputStream to String This is done using stream's write() method. Then, we simply convert the OutputStream to finalString using String 's constructor which takes byte array. For this, we use stream's toByteArray() method.

How do you write OutputStream in Java?

Methods of OutputStreamwrite() - writes the specified byte to the output stream. write(byte[] array) - writes the bytes from the specified array to the output stream. flush() - forces to write all data present in output stream to the destination. close() - closes the output stream.

Which OutputStream method is used to force a write to the stream?

The write(int b) method of OutputStream class is used to write the specified bytes to the output stream.

How do I get an OutputStream file?

FileOutputStream fout = new FileOutputStream(File file); 2. FileOutputStream( File file, boolean append): Creates a file output stream object represented by specified file object. FileOutputStream fout = new FileOutputStream(File file, boolean append);


2 Answers

You can use ByteArrayOutputStream which writes the data in memory. You can read this with a ByteArrayInputStream.

An alternative is to write an expecting OutputStream which fails as soon as you attempt to write an incorrect byte. This can be helpful to see exactly where/why a test fails.

like image 194
Peter Lawrey Avatar answered Sep 19 '22 13:09

Peter Lawrey


You could try using System.out for your output which is actually a Printstream, which is a subclass of OutputStream

see: http://docs.oracle.com/javase/6/docs/api/java/lang/System.html http://docs.oracle.com/javase/6/docs/api/java/io/PrintStream.html

like image 31
nwaltham Avatar answered Sep 19 '22 13:09

nwaltham