Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Files in Android JUnit

I am trying to create a file in the Android JUNIT testcase setup:

protected void setUp() throws Exception {
        super.setUp();

        File storageDirectory = new File("testDir");
        storageDirectory.mkdir();

        File storageFile = new File(storageDirectory.getAbsolutePath()
                + "/test.log");

        if (!storageFile.exists()) {
            storageFile.createNewFile();
        }
        mContext = new InternalStorageMockContext(storageFile);
        mContextWrapper = new ContextWrapper(mContext);
    }

I get an exception No Such File or Directory when I call createNewFile. Is there a standard way for creating files from Android JUNIT?

like image 713
ssk Avatar asked May 10 '12 17:05

ssk


1 Answers

In Android, directory/file creation and access are usually managed by Context. for instance, this is typically how we create directory file under application's internal storage:

File testDir = Context.getDir("testDir", Context.MODE_PRIVATE);

Check out the API, there are many other useful method getXXXDir() you can use for creating/accessing file.

Back to JUnit topic, suppose you use ActivityInstrumentationTestCase2 and your application project has package name com.example, and your test project has package name com.example.test:

// this will create app_tmp1  directoryunder data/data/com.example.test/,
// in another word, use test app's internal storage.
this.getInstrumentation().getContext().getDir("tmp1", Context.MODE_PRIVATE);

// this will create app_tmp2 directory under data/data/com.example/,
// in another word use app's internal storage.
this.getInstrumentation().getTargetContext().getDir("tmp2", Context.MODE_PRIVATE);

Hope this helps.

like image 69
yorkw Avatar answered Sep 28 '22 02:09

yorkw