Unable to mock BufferedWriter class in junit

前端 未结 3 502
终归单人心
终归单人心 2021-01-15 05:02

I am using a BufferedWriter object in my source code

BufferedWriter outputToErrorFile = new BufferedWriter(new FileWriter(file));
outputToErrorFile.append(\"         


        
3条回答
  •  情歌与酒
    2021-01-15 05:17

    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");
      }
    }
    

提交回复
热议问题