【问题标题】:Java and Junit integration test for file system文件系统的Java和Junit集成测试
【发布时间】:2019-03-11 13:08:40
【问题描述】:

我有这门课:

public class FooFileRepo {

@Override
public File getDirectory(String directoryPath) {
    ...     
    File directory = new File(directoryPath);
    ...
    return directory;
}

@Override
public void mkdirs(File f) {
    ...
    f.getParentFile().mkdirs();
}

public void writeFile(String path, String content) throws FileNotFoundException, UnsupportedEncodingException{
    ...
    try (PrintWriter writer = new PrintWriter(path, "UTF-8");) {
        writer.println(content);
    }
}   

}

如何模拟文件系统操作,以便为此类编写单元测试?

谢谢。

【问题讨论】:

  • 让文件指向测试资源目录中的某个东西
  • 不,因为我还要测试写文件操作。
  • 所以使用 build/target 目录并在测试后清理这个目录

标签: java junit integration-testing spring-test


【解决方案1】:

使用 PowerMock

       @RunWith(PowerMockRunner.class)
       @PrepareForTest({ Printwriter.class })
       public class SampleTestClass {

        @Mock
        private PrintWriter mockPrintWriter;

        @Before
        public void init() throws Exception {
          PowerMockito.mockStatic(FileUtils.class);
        }

        @Test
        public void test() throws IOException {
        }   
       }

【讨论】:

    【解决方案2】:

    对于这样一个简单的测试,使用真实的文件系统可能会更好。作为替代方案,您可以为文件操作构建一个外观并轻松模拟此外观。

    https://junit.org/junit4/javadoc/4.12/org/junit/rules/TemporaryFolder.html

    public static class HasTempFolder {
    @Rule
    public TemporaryFolder folder= new TemporaryFolder();
    
    @Test
    public void testUsingTempFolder() throws IOException {
      File createdFile= folder.newFile("myfile.txt");
      File createdFolder= folder.newFolder("subfolder");
      // ...
     }
    }
    

    另请阅读此答案:https://stackoverflow.com/a/17164103/516167

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      相关资源
      最近更新 更多