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 を呼び出すと、No such File or Directory という例外が発生します。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 に答える