如何在 Android unitTest/AndroidTest 中测试文件 IO

How to test file IO in Android unitTest/AndroidTest

我正在努力提高我的项目的代码覆盖率,因为我写了一个方法来使用 Android Developer 的以下代码片段将文件写入 android internalStorage网站。

String FILENAME = "hello_file";
String string = "hello world!";
File testFile = new File(context.getFilesDir(), FILENAME);
FileOutputStream fos =new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();

我的想法是通过读取文件断言并与hello world!比较,看它们是否匹配,以证明我的编写功能在单元测试/Android仪器测试中有效。但是,由于遵循

,我测试这个并不是很简单
  1. 我不知道单元测试方面(JVM)的文件路径
  2. 从 Android 仪器测试的角度来看也不是。

在 Android 中测试这种 IO 功能的最佳实践是什么?我是否应该关心文件是否已创建并放置?或者我应该简单地检查一下 fos from in not null?

FileOutputStream fos =new FileOutputStream(file);

请多多指教。谢谢。

我不会测试文件是否已保存 - 这不是您的系统,AndroidAOSP 应该进行测试以确保文件确实已保存。 Read more here

您要测试的是您是否告诉 Android 保存您的文件。大概是这样的:

String FILENAME = "hello_file";
String string = "hello world!";
File testFile = new File(context.getFilesDir(), FILENAME);
FileOutputStream fos =new FileOutputStream(file);

public void saveAndClose(String data, FileOutputStream fos) {
    fos.write(data.getBytes());
    fos.close();
}

那么您的测试将使用 Mockito 作为 FOS,并且是:

   FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
   String data = "ensure written";

   classUnderTest.saveAndClose(data, mockFos);

   verify(mockFos).write(data.getBytes());

第二次测试:

   FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
   String data = "ensure closed";

   classUnderTest.saveAndClose(data, mockFos);

   verify(mockFos).close();