'How to access cache in Android for instrumented tests?

I am doing instrumented tests on Android and I am not able to give access to the cache folder or the files folder to read and write files. I grant the permissions in the Manifest with android: requestLegacyExternalStorage =" true ", and I grant it all the permissions with the ADB idea plugin. This is the code of my tests:

 @Test
    public void createPDfOk() {

        Context con = InstrumentationRegistry.getInstrumentation().getContext();
        File f2 = new File(con.getFilesDir(), "lorem_ipsum.pdf");
        File f = new File(con.getFilesDir(), "out.pdf");
}

And the error code:

Failed to ensure /data/user/0/com.some.package.test/files: mkdir failed: EACCES (Permission denied)
Failed to ensure /data/user/0/com.some.package.test/files: mkdir failed: EACCES (Permission denied)
E/com.some.package.MainActivity: Something fail in the process
/data/user/0/com.some.package.test/files/a_pdf.pdf: open failed: EACCES (Permission denied)


Solution 1:[1]

There are no cache or files directories in the instrumented tests app. You can use directories from the main app.

@Test
public void createPDfOk() {
    Context targetCtx = InstrumentationRegistry.getInstrumentation().getTargetContext();

    File f2 = new File(targetCtx.getFilesDir(), "lorem_ipsum.pdf");
    File f = new File(targetCtx.getFilesDir(), "out.pdf");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vilius Sutkus '89