pixel
pixel

Reputation: 26513

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

Upvotes: 4

Views: 1584

Answers (2)

vgonisanz
vgonisanz

Reputation: 11940

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.

Upvotes: 3

mbob
mbob

Reputation: 630

Assuming you have a file under src/androidTest/assets/myasset.txt you would access it like InstrumentationRegistry.getContext().getResources().getAssets().open("myasset.txt");

Upvotes: -1

Related Questions