6

我正在尝试在 Android JUNIT 测试用例设置中创建一个文件:

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);
    }

当我调用 createNewFile 时,我得到一个异常没有这样的文件或目录。是否有从 Android JUNIT 创建文件的标准方法?

4

1 回答 1

10

在 Android 中,目录/文件的创建和访问通常由Context管理。例如,这通常是我们在应用程序的内部存储下创建目录文件的方式:

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

查看 API,还有许多其他有用的方法 getXXXDir() 可用于创建/访问文件。

回到 JUnit 主题,假设您使用 ActivityInstrumentationTestCase2 并且您的应用程序项目具有包名称com.example,并且您的测试项目具有包名称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);

希望这可以帮助。

于 2012-05-10T21:42:52.080 回答