0

I have a method that writes out to a word doc using Apache POI API. The issue I am having is, I want to test the method without creating an external document. The method that creates the document is the .write(OutputStream).

I need to find a way to get that method to doNothing() but when I have tried to mock the XWPFDocument, I get errors that there were 0 invocations on the mock.

Here is the method I am trying to test:

public String populateDoc(String text) {
    try (XWPFDocument doc = new XWPFDocument();
         OutputStream out = Files.newOutputStream(OUT)) {
        StringBuilder sb = new StringBuilder();
        LOGGER.info("Document Created.");
        String[] lines = text.split("\n");
        for (String line : lines) {
            XWPFParagraph para = doc.createParagraph();
            XWPFRun run = para.createRun();
            run.setText(line);
            sb.append(line);
            sb.append("\n");
        }
        LOGGER.info("Document saved.");
        doc.write(out);
        return sb.toString();
    } catch (IOException ioe) {
        LOGGER.error(ioe);
    }
    return null;
}

The test I have right now that creates an external document which I don't want:

@ExtendWith(MockitoExtension.class)
public class FileWriterTest {
    @Test
    void testFileContainsAParagraph() {
        FileWriter fileWriter = new FileWriter("src/test/resources/outputTest.docx");
        String text = "Hello World.\n";

        Assertions.assertEquals(text, fileWriter.populateDoc(text));
    }
}

What I have tried:

@Test
void testTextReturnsHello() throws IOException {
    XWPFDocument doc = mock (XWPFDocument.class);
    FileWriter fileWriter = new FileWriter();
    OutputStream out = Files.newOutputStream(Paths.get("src/test/resources/outputTest.docx"));
    String text = "Hello";
    Mockito.doNothing().when(doc).write(out);
    
    Assertions.assertEquals(text, fileWriter.populateDoc(text));
    
    Mockito.verify(doc).write(out);
}

Error I get:

org.mockito.exceptions.base.MockitoException: 
Only void methods can doNothing()!
Example of correct use of doNothing():
    doNothing().
    doThrow(new RuntimeException())
    .when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
AceKokuren
  • 41
  • 8

0 Answers0