首页 > 解决方案 > 从 androidTest 读取 json 文件

问题描述

您好,我正在尝试读取位于 androidTest 资源文件夹中的 json 文件。我可以访问位于 Test/resources 中的资源文件夹中的 json 文件,但不能访问 androidTest/resources 中的 json 文件。

我使用以下方法获取 Test/resources 文件夹中的 json 文件。

private fun getJson(path: String): String {
    val uri = this.javaClass.classLoader?.getResource(path)
    val file = File(uri?.path ?: "")
    return String(file.readBytes())
}

有没有办法可以访问 androidTest/resources 下的文件?在此处输入图像描述

标签: androidandroid-resourcesandroid-testing

解决方案


 private fun getJson(fileName: Int): String {
        val inputStream = InstrumentationRegistry.getInstrumentation().targetContext.resources.openRawResource(fileName)
        val s = Scanner(inputStream).useDelimiter("\\A")
        return if (s.hasNext()) s.next() else ""
    }

推荐阅读