在 Android Instrumentation 上下文中写入/创建文件

问题描述 投票:0回答:2

我有一个类,它创建(或打开)一个文件以向其中写入一些数据。该类在构造函数中接收一个 Context,将其保存在实例字段中,然后使用它来调用 context.openFileOutput 方法。

运行应用程序时,我通过将 ApplicationContext 作为上下文传递来实例化此类,一切都按预期工作。

但是,当我尝试使用仪器测试来测试此类时,我得到了

NullPointerException
。我正在传递
getInstrumentation().getContext()
上下文,我知道它对应于测试的上下文,而不是真实应用程序的上下文。

getInstrumentation().getContext().openFileOutput("myFile", Context.MODE_PRIVATE); // This throws NullPointerException :( :(

在测试中,我需要在测试包中而不是在应用程序包中创建此文件,因为我不想覆盖我的应用程序中的文件。

我知道那里有一个

RenamingDelegatingContext
类,但我无法将此上下文传递给我的类,因为我的类也打开了原始资源,并且我希望该资源在运行测试时有所不同(类似于模拟资源) .

我对此进行了很多搜索,并且没有关于 Instrumentation Context 的文档。我找不到它的局限性,也找不到任何可以解决我的问题的东西。

你知道如何解决这个问题吗?

android testing android-context instrumentation
2个回答
0
投票
import android.content.Context;
import android.os.Environment;
import androidx.test.platform.app.InstrumentationRegistry;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCreator {

    public void createFile() {
        // Get the instrumentation context
        Context context = InstrumentationRegistry.getInstrumentation().getContext();

        // Define the file name
        String fileName = "myFile.txt";

        // Get the directory
        File directory = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);

        // Create a new file
        File file = new File(directory, fileName);

        try {
            // Create a FileOutputStream
            FileOutputStream fos = new FileOutputStream(file);

            // Write some data
            fos.write("Hello, World!".getBytes());

            // Close the FileOutputStream
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

此代码在

myFile.txt
目录中创建一个名为
DIRECTORY_DOCUMENTS
的新文件,并向其中写入字符串 Hello, World!

请确保您拥有写入外部存储的必要权限。您可能需要将 <

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
添加到您的
AndroidManifest.xml
文件中。另外,请记住在生产代码中适当处理异常。


-1
投票

我不记得什么时候改变了,但在仪器测试期间获取

Context
对象的当前方法是导入

import android.support.test.InstrumentationRegistry;

并致电

InstrumentationRegistry.getContext();

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.