Android Studio unit testing: read data (input) file

63,641

Solution 1

Depending on android-gradle-plugin version:

1. version 1.5 and higher:

Just put json file to src/test/resources/test.json and reference it as

classLoader.getResource("test.json"). 

No gradle modification is needed.

2. version below 1.5: (or if for some reason above solution doesn't work)

  1. Ensure you're using at least Android Gradle Plugin version 1.1. Follow the link to set up Android Studio correctly.

  2. Create test directory. Put unit test classes in java directory and put your resources file in res directory. Android Studio should mark them like follow:

    enter image description here

  3. Create gradle task to copy resources into classes directory to make them visible for classloader:

    android{
       ...
    }
    
    task copyResDirectoryToClasses(type: Copy){
        from "${projectDir}/src/test/res"
        into "${buildDir}/intermediates/classes/test/debug/res"
    }
    
    assembleDebug.dependsOn(copyResDirectoryToClasses)
    
  4. Now you can use this method to get File reference for the file resource:

    private static File getFileFromPath(Object obj, String fileName) {
        ClassLoader classLoader = obj.getClass().getClassLoader();
        URL resource = classLoader.getResource(fileName);
        return new File(resource.getPath());
    }
    
    @Test
    public void fileObjectShouldNotBeNull() throws Exception {
        File file = getFileFromPath(this, "res/test.json");
        assertThat(file, notNullValue());
    }
    
  5. Run unit test by Ctrl+Shift+F10 on whole class or specyfic test method.

Solution 2

For local unit tests (vs. instrumentation tests), you can put files under src/test/resources and read them using classLoader. For example, following code opens myFile.txt file in the resources directory.

InputStream in = this.getClass().getClassLoader().getResourceAsStream("myFile.txt");

It worked with

  • Android Studio 1.5.1
  • gradle plugin 1.3.1

Solution 3

In my case, the solution was to add to the gradle file

sourceSets {
    test.resources.srcDirs += 'src/unitTests/resources'
  } 

After it everything was found by AS 2.3.1

javaClass.classLoader.getResourceAsStream("countries.txt")

Solution 4

I though I should add my findings here. I know this is a little old but for the newer versions of Gradle, where there is NO src/test/resources directory, but only one single resources directory for the whole project, you have to add this line to your Gradle file.

android {
   testOptions {
      unitTests {
         includeAndroidResources = true
      }
    }
}

By doing this you can access your resource with:

 this.getClass().getClassLoader().getResourceAsStream(fileName);

I've been searching for this and could not find an answer, so I decided to help others here.

Solution 5

I've had plenty of problems with test resources in Android Studio so I set up a few tests for clarity. In my mobile (Android Application) project I added the following files:

mobile/src/test/java/test/ResourceTest.java
mobile/src/test/resources/test.txt
mobile/src/test/resources/test/samePackage.txt

The test class (all tests passes):

assertTrue(getClass().getResource("test.txt") == null);
assertTrue(getClass().getResource("/test.txt").getPath().endsWith("test.txt"));
assertTrue(getClass().getResource("samePackage.txt").getPath().endsWith("test/samePackage.txt"));
assertTrue(getClass().getResource("/test/samePackage.txt").getPath().endsWith("test/samePackage.txt"));
assertTrue(getClass().getClassLoader().getResource("test.txt").getPath().endsWith("test.txt"));
assertTrue(getClass().getClassLoader().getResource("test/samePackage.txt").getPath().endsWith("test/samePackage.txt"));

In the same root project I have a Java (not Android) project called data. If I add the same files to the data project:

data/src/test/java/test/ResourceTest.java
data/src/test/resources/test.txt
data/src/test/resources/test/samePackage.txt

Then all the tests above will fail if I execute them from Android Studio, but they pass on the command line with ./gradlew data:test. To get around it I use this hack (in Groovy)

def resource(String path) {
    getClass().getResource(path) ?:
            // Hack to load test resources when executing tests from Android Studio
            new File(getClass().getClassLoader().getResource('.').path
                    .replace('/build/classes/test/', "/build/resources/test$path"))
}

Usage: resource('/test.txt')

Android Studio 2.3, Gradle 3.3

Share:
63,641

Related videos on Youtube

Frank
Author by

Frank

Updated on May 03, 2022

Comments

  • Frank
    Frank about 2 years

    In a unit test, how can I read data from a json file on my (desktop) file system, without hardcoding the path?

    I would like to read test input (for my parsing methods) from a file instead of creating static Strings.

    The file is in the same location as my unit testing code, but I can also place it somewhere else in the project if needed. I am using Android Studio.

    • Frank
      Frank about 9 years
      I tried almost every combination with IOUtils.toString( this.getClass().getResourceAsStream("test_documents.json"), "UTF-8"), it always returns null. Probably because the files won't get included in the jar.
    • AndroidEx
      AndroidEx about 9 years
      Are we talking about unit tests involving android emulator/device?
    • akhy
      akhy about 9 years
      @Android777 I think we're talking about new unit test support introduced in recent version of Android Studio tools.android.com/tech-docs/unit-testing-support
    • akhy
      akhy about 9 years
      @Frank where do you place test_documents.json? assets directory?
    • Frank
      Frank about 9 years
      Yes, we are talking about the new unit test support, not involving the emulator/device. I did not place it in the assets dir, because then it gets packaged with the live apk. I placed it in the same folder as the test (java) files.
    • klimat
      klimat about 9 years
      @Frank I've updated my answer, it should satisfy you.
  • Frank
    Frank about 9 years
    and than use this.getClass().getResourceAsStream(test.json) ? I added the files there, in the root of the project, it still does not find the files.
  • Frank
    Frank about 9 years
    Awesome! Your edit, without instrumentaltests, works like a charm, thanks!
  • David Vávra
    David Vávra about 9 years
    After 2 hours of fighting with Roboelectric, this simple solution did it.
  • joaoprudencio
    joaoprudencio almost 9 years
    It's a nice solution, but it doesn't work always. If you perform run the clean task, and then run testDebug it fails. Basically the developer needs to know that he must run the assembleDebug task before testDebug. Do you guys have any suggestion to improve this?
  • Rakshith N
    Rakshith N over 8 years
    This solution worked for me WITHOUT the gradle changes by putting the files under test/res/assets and getClass().getClassLoader().getResourceAsStream("assets/" + jsonFile)
  • Sergii Pechenizkyi
    Sergii Pechenizkyi over 8 years
    With AndroidStudio 1.5 with android plugin 1.5.0 place your json file here src/test/resources/test.json and reference it as classLoader.getResource("test.json"). No gradle modification is needed. Nested folders inside resources are working also.
  • Bhargav
    Bhargav over 8 years
    @joaoprudencio can you make this task depend on a task that is run every time you run a unit test?
  • Tyler Pfaff
    Tyler Pfaff about 8 years
    This isn't working for me please see my question here stackoverflow.com/questions/36295824/…
  • Tyler Pfaff
    Tyler Pfaff about 8 years
    This isn't working for me please see my question here stackoverflow.com/questions/36295824/…
  • Alex Bravo
    Alex Bravo about 8 years
    This worked for me, when I changed from "src/test/res" to "src/test/resources". Using Android Studio 2.0 RC 3, gradle:2.0.0-rc3
  • Zach
    Zach over 7 years
    This definitely works and is good - but now I see a "resources" folder in my app hierarchy. It's not clear that it's associated with test resources at all (i.e. no (test) label next to it like the test java folders are). Is there a way to "clean" this up? Maybe move the location of this folder? add that label so I don't get confused with the "res" folder that Android uses for regular app resources, etc?
  • M. Reza Nasirloo
    M. Reza Nasirloo over 7 years
    Could not get unknown property 'assembleDebug' for project ':app' of type org.gradle.api.Project. any idea?
  • voghDev
    voghDev over 7 years
    Incomplete answer. What is classLoader? where to place this line of code? what can you do with the return result?. Please provide more complete code. -1
  • voghDev
    voghDev over 7 years
    That's true, but you could at least complete the code with the test method header (so reader knows it goes inside a test), and assign it to an InputStream, or any other object as other answers did. Honestly, I read the answer this morning and had to spend time reading the method signature, documentation, etc. I would expect something more helpful. That's why I encourage you to improve it
  • mm2001
    mm2001 about 7 years
    Great answer (after 45 mins of searching 😌). It gets to the heart of several issues and makes it easy to replicate the results using the tests themselves. Fwiw, In AS 2.3.1, Gradle 2.3.1, the getClassLoader() versions work as expected. I.e. they find the files, both run from Android Studio AND from the command line on my macOS machine, and on the Linux CI server (CircleCI). So I'm going with that and hoping Gradle 3.3 doesn't break it later...
  • DoronK
    DoronK about 7 years
    @ joaoprudencio Commenting out testCoverageEnabled true did the trick for me. buildTypes { debug { // testCoverageEnabled true } }
  • Mark McKenna
    Mark McKenna about 7 years
    Nice! I'm seeing the same resource loading issue here. AS 2.3.2, Gradle 3.3. The tests work from the command line but not through AS, due to build/resources/test not being included in the interactive classpath.
  • Mark McKenna
    Mark McKenna about 7 years
    This can be used to load files using new File() or similar, but it doesn't work directly with the classpath loading method described above. It's also a bit tricky because each new run configuration needs to set the working dir, and by default AS and Gradle command line like to use different working dirs... such a pain
  • Les
    Les almost 7 years
    when nesting resources, use a forward slash (/) even on Windows
  • anand krish
    anand krish over 6 years
    worked as expected. But test is getting pass even if file is not avail under "src/test/resources/" eg:"rules.xml", but InputStream results null in this case.
  • Ihor Klimov
    Ihor Klimov over 6 years
    If you get NullPointerException or NoSuchFileException - make sure your directory is called resources, not res. And here's the way you get this file URL resource = this.getClass().getClassLoader().getResource("file.txt"); File f = new File(resource.toURI());
  • Rob Drimmie
    Rob Drimmie about 6 years
    Just in case anyone else struggles, I was confused for a little while because I was adding the folder while in "Android" view of the project, instead of "Project" view. As a result, I'd created it as src/test/java/com.example/resources - it was with all my tests, instead of in the root of the tests.
  • Erik
    Erik over 5 years
    To read ./src/test/resources/file.txt in Kotlin: TestClassName::class.java.getResource("/file.txt")!!.readTex‌​t()
  • jj.
    jj. over 5 years
    kotlin: val myFile = ClassLoader.getSystemResource("myFile.txt").readText()
  • jj.
    jj. over 5 years
    I did something very similar (Kotlin): 1. create folder and file at: root/app/src/test/resources/test.json 2. read data like this: val jsonFile = ClassLoader.getSystemResource("test.json").readText()
  • Amit Bhandari
    Amit Bhandari over 5 years
    Worked like charm!
  • desgraci
    desgraci over 4 years
    Caused by: java.lang.IllegalArgumentException: UTF8 string too large, not the best way to do it
  • Martin Nowosad
    Martin Nowosad over 3 years
    thank you Raphael Ayres. This should be the top voted comment. Also, you need to create your resources directory under src/test/, so you'll end up having src/test/resources/...
  • Guillermo Tobar
    Guillermo Tobar about 3 years
    @joaoprudencio only replace "assembleDebug" with "build".
  • display name
    display name about 3 years
    This works fine for instrumented tests. Did this work for you in the unit test (no instrumentation test)?
  • Damn Vegetables
    Damn Vegetables over 2 years
    @displayname Watch this question. I wondered the same thing.