Ed_
Ed_

Reputation: 1730

Where does Robolectic on Android, save files created during test runs?

I want to ensure a byte array is being converted to a jpg correctly.

I've simplified the problem as follows:

public String saveToFile(String filename, String contents) {
    String storageState = Environment.getExternalStorageState();

    if(!storageState.equals(Environment.MEDIA_MOUNTED)) {
        throw new IllegalStateException("Media must be mounted");
    }

    File directory = Environment.getExternalStorageDirectory();
    File file = new File(directory, filename);
    FileWriter fileWriter;

    try {
        fileWriter = new FileWriter(file, false);
        fileWriter.write(contents);
        fileWriter.close();

        return file.getAbsolutePath();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

@Test
public void testDummyTest() throws Exception{
    String out = saveToFile("preview-test.jpg", "preview-test.jpg");
}

This test passes and the path is something like file:///var/folders/z_/_syx1dpx7v9_pmktgdbx7f_m0000gn/T/android-external-cache8656399524188278404robolectric/ddf1c2ec-c0a8-44ce-90e4-7de2a384c57f/preview-test.jpg However, I can't find this file my machine (yes, I've searched for it). I suspect this is a temp cache and its being cleared/deleted before I can view it.

Please can you tell me how to locate the "preview-test.jpg" file so I may open it in an image viewer, thus proving the image looks like it should. Thanks.

Note: the problem is not the jpg encoding, its simply getting direct access to the file.

Upvotes: 3

Views: 1173

Answers (1)

Ed_
Ed_

Reputation: 1730

I found a partial solution.

Rather than using the shadow environment to provide a path, I can instead use an absolute path for the machine. Eg root "/" would work.

So the code would look something like...

public String saveToFile(String filename, String contents) throws IOException {

    File file = new File("/", filename);
    FileWriter fileWriter;

    fileWriter = new FileWriter(file, false);
    fileWriter.write(contents);
    fileWriter.close();

    return file.getAbsolutePath();

}

@Test
public void testDummyTest() throws Exception {
    String out = saveToFile("preview-test.jpg", "preview-test.jpg");

}

This then leaves a file on the root directory of the machine. :) Hope this helps somebody else out there.

Upvotes: 4

Related Questions