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

IHC*_*oid 1 android unit-testing android-instrumentation

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

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();
Run Code Online (Sandbox Code Playgroud)

我的想法是通过读取文件并与之进行比较hello world!并查看它们是否匹配来证明我的书写功能在单元测试/ Android Instrumentation测试中有效.但是,由于以下原因,对我来说测试这个并不是一件容易的事

  1. 我不知道单元测试方面(JVM)的文件路径
  2. 不是从Android仪器测试的角度来看.

在Android中测试此类IO功能的最佳做法是什么?我是否应该关心文件是否已创建并放入?或者我只是检查一下是否为fos空?

FileOutputStream fos =new FileOutputStream(file);
Run Code Online (Sandbox Code Playgroud)

请给我提供建议.谢谢.

Blu*_*ell 5

我不会测试该文件是否已保存 - 这不是您的系统,Android AOSP应该进行测试以确保文件实际保存.在这里阅读更多

您要测试的是,如果您要告诉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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

   classUnderTest.saveAndClose(data, mockFos);

   verify(mockFos).write(data.getBytes());
Run Code Online (Sandbox Code Playgroud)

第二次测试:

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

   classUnderTest.saveAndClose(data, mockFos);

   verify(mockFos).close();
Run Code Online (Sandbox Code Playgroud)