如何在Java中模拟文件IO?

我怎样才能创建一个模仿java.io.File文件读写的MockFile类? 我在任何地方使用我自己的方法而不是new FileInputStream(....)new FileOutputStream(....) ,所以这部分没问题(我总是委托给相应的流)。 非trivila部分是在更复杂的情况下我的MockFileInputStreamMockFileOutputStream的实现。

没问题,当我第一次写入文件然后读取它时,我可以简单地使用ByteArrayOutputStream等等。 这很简单,但是通过交错读写,它无法正常工作。 比编写我自己的ByteArrayOutputStream版本更好的想法?

我创建了一个’WordCounter’类来计算文件中的单词。 但是,我想对我的代码进行unit testing,unit testing不应该触及文件系统。

因此,通过将实际的文件IO(FileReader)重构为它自己的方法(让我们面对它,标准的Java文件IO类可能工作,所以我们通过测试它们没有获得太多收益)我们可以单独测试我们的字计数逻辑。

 import static org.junit.Assert.assertEquals; import java.io.*; import org.junit.Before; import org.junit.Test; public class WordCounterTest { public static class WordCounter { public int getWordCount(final File file) throws FileNotFoundException { return getWordCount(new BufferedReader(new FileReader(file))); } public int getWordCount(final BufferedReader reader) { int wordCount = 0; try { String line; while ((line = reader.readLine()) != null) { wordCount += line.trim().split(" ").length; } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } return wordCount; } } private static String TEST_CONTENT = "Neque porro quisquam est qui dolorem\n" + " ipsum quia dolor sit amet, consectetur, adipisci velit..."; private WordCounter wordCounter; @Before public void setUp() { wordCounter = new WordCounter(); } @Test public void ensureExpectedWordCountIsReturned() { assertEquals(14, wordCounter.getWordCount(new BufferedReader(new StringReader(TEST_CONTENT)))); } } 

编辑 :我应该注意,如果你的测试与你的代码共享相同的包,你可以降低其可见性

 public int getWordCount(final BufferedReader reader) 

方法,因此您的公共API只公开

 public int getWordCount(final File file) 

我会使用一个真实的文件和一个真正的FileInputStreamFileOutputStream 。 否则你只是在练习测试代码:真的很无趣。