Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

junit

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
    ...

}
like image 261
Kamilski81 Avatar asked May 14 '16 01:05

Kamilski81


People also ask

How do you write JUnit test cases for Android?

You write your local unit test class as a JUnit 4 test class. To do so, create a class that contains one or more test methods, usually in module-name/src/test/ . A test method begins with the @Test annotation and contains the code to exercise and verify a single aspect of the component that you want to test.

How do I read a file from test resources folder?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().


1 Answers

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.

like image 169
rharter Avatar answered Oct 13 '22 01:10

rharter