0

I have similar issue which is Listed in Mocking fields inside of a method in Junit 5 . However I see that it's marked as duplicate. If I go to the posts pointed in the above link, they don't answer the issue i'm facing.

I have a ServiceProvider with a function generate file

public class ServiceProvider {

    public void generateFileUsingOutputStream() {
        try {
            OutputStreamWriter oWriter = new OutputStreamWriter(Files.newOutputStream(""/tmp/sample/test.txt""), StandardCharsets.UTF_8);
            oWriter.write("hellow");
            oWriter.close();
            System.out.println("File generated");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Path listed in the above function is generated dynamically in the code. I have a Junit test for the above function, which actually fails because folder /tmp/sample/ doesn't exist. Is it possible to mock OutputStreamWriter in the Junit so that the above function works without checking for the file existence?

class ServiceProviderTest {

    @Test
    void testFile() throws Exception {
        
        serviceProvider.generateFileUsingOutputStream();
    }
}
Mattravel
  • 1,358
  • 1
  • 15
CODE45
  • 1
  • Not a duplicate of your question, but still offers many solutions that apply to your problem as well: [Why are my mocked methods not calld when executing a unit test?](https://stackoverflow.com/q/74027324/112968) – knittl Mar 01 '23 at 19:51

0 Answers0