Kamilski81
Kamilski81

Reputation: 15107

How do I access a text file for JUnit test in Android?

How can I access a text file in my directory 'src/test/resources'

I can't seem to get it to pickup during my JUnit test

mobile/build.gradle:

sourceSets {
        test {
            java {
                srcDirs = [ 'src/test/java' ]
            }
            resources {
                srcDirs = [ 'src/test/resources' ]
            }
        }
    }

Test method:

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

}

Upvotes: 6

Views: 4993

Answers (3)

rharter
rharter

Reputation: 2495

Prefix the file path with /.

Basically, you'd do something like this:

File helloBleprintJson = new File(
        getClass().getResource("/helloBlueprint.json").getPath());

Above snippet is taken from here.

Upvotes: 8

Pomagranite
Pomagranite

Reputation: 696

Forgive me for posting twice, I do have an answer from the official documentation" Arbitrary files to save in their raw form. To open these resources with a raw InputStream, call Resources.openRawResource() with the resource ID, which is R.raw.filename.

However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/). Files in assets/ are not given a resource ID, so you can read them only using AssetManager." Json and txt are non-standard(unsupported) so you have to provide your own implementation/parcer to read this type file. Thanks for this post. I knew something about resources but thanks to your prodding now I know even more. To recap The Android resource system keeps track of all non-code assets associated with an application. The Android SDK tools compile your application's resources into the application binary at build time. To use a resource, you must install it correctly in the source tree (inside your project's res/ directory) and build your application. As part of the build process, the SDK tools generate symbols for each resource, which you can use in your application code to access the resources and of course the symbols referred to are in the generated R file

Upvotes: 0

Pomagranite
Pomagranite

Reputation: 696

I think this link will help. In your case why not hard code strings for testing? Why not use String.xml instead of "file_four_lines.txt". Internationalization requires a directory structure for each resource file having different language, screen size, orientation, flavor, night/day vision version. For this reason resources are compiled and accessed from the R file. You are trying to bypass this convention by using .txt instead of .xml and accessing the resource directly, it just feels wrong. I don't think testing is you problem as much as not following convention.

Upvotes: 0

Related Questions