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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With