I am using a BufferedWriter object in my source code
BufferedWriter outputToErrorFile = new BufferedWriter(new FileWriter(file));
outputToErrorFile.append(\"
I wouldn't mock BufferedWritter at all. Create a writer backed by a ByteArrayOutputStream in your test, pass it to the class you are testing, then inspect it when you are done. This may require refactoring your code to create a seam for testing. Here's one possible implementation:
public void writeToWriter(Writer writer) {
writer.append("some string");
}
Then your test can look like this:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(stream, charset);
objectUnderTest.writeToWriter(writer);
String actualResult = writer.toString(charset);
assertEquals("some string", actualResult);
If the method you are testing needs to open and close the stream, I'm fond of using Guava's CharSink class:
public void writeToSink(CharSink sink) {
try (Writer writer = sink.openBufferedStream()) {
writer.append("some string");
}
}