Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access File object from test assets in Android instrumentation tests?

I would like to read File object somehow in Android instrumentation tests.

I'm trying to get it using assets folder located in androidTest

File("//android_asset/myFile.jpg")

Unfortunately I cannot get this file. Is anyone aware how to create such File object? It does not necessarily have to be located in assets

like image 748
pixel Avatar asked Nov 01 '25 19:11

pixel


1 Answers

If you need to copy a file in the device, in example for test a C++ library that require the path to a file instead a stream, you can copy manually in this way:

    @Test
    public void checkFileWorkingTxt() throws IOException {
        String path = "filepath.txt";
        Context context = InstrumentationRegistry.getTargetContext();

        // Creation of local file.
        InputStream inputStream = context.getResources().getAssets().open(path);

        // Copy file to device root folder
        File f = new File(context.getExternalCacheDir() + path);
        FileOutputStream outputStream = new FileOutputStream(f);
        FileUtils.copy(inputStream, outputStream);

        // Check that everything works with native function
        bool result = NativeLibrary.check_txt(f.getAbsolutePath());
        assertTrue(result);
    }

This may be not the best way but it works.

like image 75
vgonisanz Avatar answered Nov 04 '25 11:11

vgonisanz