Как издеваться над FileWriter в Junit 5 - PullRequest
0 голосов
/ 28 мая 2020

Я пытаюсь имитировать FileWriter, чтобы мой тест не создал файл. Код работает обычным образом, но я не могу создать правильный тест.

JSONExporter

    public void exportFile(List<Employee> employeeList) throws ExportFileException {
    try (Writer writer = new FileWriter("filepath")) {
        Gson gson = new GsonBuilder()
                .setPrettyPrinting()  //prints the json file with json indenting
                .create();
        gson.toJson(employeeList, writer);
    } catch (IOException ex) {
        throw new ExportFileException();
    }
}

TestJSONExporter

 @Injectable FileWriter mockedFileWriter;
@Test
void testExportFile_whenFilenameIsValid_willDoNothing(@Mocked Gson mockedGson) throws IOException {
    new Expectations() {{
        new FileWriter(anyString); result = mockedFileWriter;
        mockedGson.toJson(any, (FileWriter) any);
    }};
    Assertions.assertDoesNotThrow( () -> jsonFileExporter.exportFile("filename", Role.SELLER, employeeList));
}

Консоль

java.io.FileNotFoundException:  (Result too large)

at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at java.io.FileWriter.<init>(FileWriter.java:63)
at com.eurodyn.training.export.JSONFileExporterTest$1.<init>(JSONFileExporterTest.java:59)
at com.eurodyn.training.export.JSONFileExporterTest.testExportFile_whenFilenameIsValid_willDoNothing(JSONFileExporterTest.java:58)

Кто-нибудь знает, есть ли способ сделать это с помощью jmockit или mockito. Я думаю, PowerMock несовместим с JUnit 5.

...