Search code examples
androidstorage-access-frameworkscoped-storage

Unit testing SAF file/directory operations


I am trying to implement unit tests for Android code that utilizes DocumentFile instances for file/directory operations. Normally it would be possible to initiate these tests by picking a location using ACTION_OPEN_DOCUMENT_TREE, but I am unable to get an instance of DocumentFile as part of such unit test (without needing user interaction).

It would be perfectly sufficient for my use case if I were able to convert a location in application's private storage to DocumentFile, but converting a file:// URI of a directory to DocumentFile does not seem possible.


Solution

  • The documentation for DocumentFile.fromFile() is less than clear, but it works for files and directories. As opposed to Uri values — where you need to call fromSingleUri() or fromTreeUri() to distinguish documents from trees — fromFile() can figure that out on its own.