How to unit test a method that reads a given file

前端 未结 4 1192
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 23:55

I know this is a bit naive. How to unit test this piece of code without giving physical file as input. I am new to mockito and unit testing. So I am not sure. Please help.

4条回答
  •  情书的邮戳
    2021-01-02 00:42

    You can create a file as part of the test, no need to mock it out.

    JUnit does have a nice functionality for creating files used for testing and automatically cleaning them up using the TemporaryFolder rule.

    public class MyTestClass {
    
        @Rule
        public TemporaryFolder folder = new TemporaryFolder();
    
        @Test
        public void myTest() {
            // this folder gets cleaned up automatically by JUnit
            File file = folder.newFile("someTestFile.txt");
    
            // populate the file
            // run your test
        }
    }
    

提交回复
热议问题