如何在Android中访问JUnit测试的文本文件?

Kam*_*i81 4 junit android

如何访问我的目录'src/test/resources'中的文本文件

在我的JUnit测试中,我似乎无法获取它

移动/的build.gradle:

sourceSets {
        test {
            java {
                srcDirs = [ 'src/test/java' ]
            }
            resources {
                srcDirs = [ 'src/test/resources' ]
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

测试方法:

@Test
public void test_file() {
    URL resource = getClass().getResource("file_four_lines.txt");
    File file = new File(resource.getFile()); // Get NullPointerException here
    ...

}
Run Code Online (Sandbox Code Playgroud)

rha*_*ter 6

使用前缀文件路径/.

基本上,你会做这样的事情:

File helloBleprintJson = new File(
        getClass().getResource("/helloBlueprint.json").getPath());
Run Code Online (Sandbox Code Playgroud)

上面的片段取自此处.