Alex Rivera | Logout

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

Asked 2012-02-17T12:26:42.417
12

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

Edit
Report

1 Answer

0

You should have the mocked getOutputStream(String) return a java.io.StringWriter and you can then assert that the expected content was written.

public void testFileWrite() throws IOException {
    StringWriter writer = new StringWriter();
    when(testObj.getOutputStream(outputFileNameValidValue)).thenReturn(writer);

    testObj.write(outputFileNameValidValue, reveredFileInput);

    assertEquals(reveredFileInput, writer.toString());

    verify(writer).close();
}
answered 2012-02-18T03:05:29.693

Your Answer