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
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.
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.
The write(int b) method of OutputStream class is used to write the specified bytes to the output stream.
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);
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.
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
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