ChatGPT解决这个技术问题 Extra ChatGPT

Android Studio unit testing: read data (input) file

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.

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.
Are we talking about unit tests involving android emulator/device?
@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
@Frank where do you place test_documents.json? assets directory?
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.

k
klimat

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)

Ensure you're using at least Android Gradle Plugin version 1.1. Follow the link to set up Android Studio correctly. 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: 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) 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()); } Run unit test by Ctrl+Shift+F10 on whole class or specyfic test method.


Awesome! Your edit, without instrumentaltests, works like a charm, thanks!
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?
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.
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
To read ./src/test/resources/file.txt in Kotlin: TestClassName::class.java.getResource("/file.txt")!!.readText()
u
user3113045

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


This isn't working for me please see my question here stackoverflow.com/questions/36295824/…
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
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.
kotlin: val myFile = ClassLoader.getSystemResource("myFile.txt").readText()
Worked like charm!
a
ar-g

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")

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()
R
Raphael Ayres

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.


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/...
L
Love

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


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...
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.
T
Tas Morf

If you go to Run -> Edit configurations -> JUnit and then select the run configuration for your unit tests, there is a 'Working directory' setting. That should point to wherever your json file is. Keep in mind this might break other tests.


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

Actually, this is what worked for me with Instrumentation Tests (Running Android Studio version 3.5.3, Android Gradle Plugin version 3.5.3, Gradle version 6.0.1):

Put your files in src/androidTest/assets folder In your test file:

InputStream is = InstrumentationRegistry.getInstrumentation().getContext().getAssets().open("filename.txt");


This works fine for instrumented tests. Did this work for you in the unit test (no instrumentation test)?
@displayname Watch this question. I wondered the same thing.
V
Vikash Kumar Tiwari

Step(1) open Android Studio select Project view

Step(2) and create resources directory under test.

Please look at attached screenshot for Step(2) result

https://i.stack.imgur.com/Ord6b.png

Step(3) put json file into resources folder(app/src/test/resources)

Please look at attached screenshot for Step(3) result

https://i.stack.imgur.com/GaDeE.png

Step(4) Create a common class to handle reading local json files and converting to respective models using Gson

Example :-

object TestHelper {
    private val gson = Gson()

    fun loadJsonAsString(fileName: String): String {
        val inputStream = javaClass.getResourceAsStream("/$fileName")
        return getStringFromInputStream(inputStream)
    }

    @Throws(IOException::class)
    private fun getStringFromInputStream(stream: InputStream?): String {
        var n = 0
        val buffer = CharArray(1024 * 4)
        val reader = InputStreamReader(stream, "UTF8")
        val writer = StringWriter()
        while (-1 != reader.read(buffer).also { n = it }) writer.write(buffer, 0, n)
        return writer.toString()
    }

    fun <T> convertJsonToModel(jsonString: String, classT: Class<T>): T{
        return gson.fromJson(jsonString, classT)
    }
}

Step(5) load the json file stored locally in resources directory created in Step(2)

val GET_USER_INFORMATION_RESPONSE_FILE_NAME = "user_response.json"
val jsonString = loadJsonAsString(GET_USER_INFORMATION_RESPONSE_FILE_NAME)
        val networkStatusResponse =
            convertJsonToModel(jsonString, UserResponse::class.java)

Step(6) at the end of Step(5) you would have converted local json file into required model class that can be used to write your unit tests.


N
Nicola Gallazzi

In my case I only needed to create resources folder into test folder and put my resource file in that folder. Then, in the test simply load the file as resource stream with:

val inputStream =
        this.javaClass.classLoader?.getResourceAsStream("gallery.xml")

https://i.stack.imgur.com/n50b7.png

Reference on medium: https://medium.com/mobile-app-development-publication/android-reading-a-text-file-during-test-2815671e8b3b