To read from a json file in resources folder of test folder, i use
sourceSets {
val sharedTestDir = "src/test-shared/java"
getByName("test") {
java.srcDir(sharedTestDir)
}
getByName("androidTest") {
java.srcDir(sharedTestDir)
resources.srcDir("src/test/resources")
}
}
and in test-shared folder i use extension functions to convert json file to objects
fun getResourceAsText(path: String): String {
return object {}.javaClass.classLoader!!.getResource(path)!!.readText()
}
inline fun <reified T> convertToObjectFromString(input: String): T? {
return Gson().fromJsonWithType<T>(input)
}
inline fun <reified T> Gson.fromJsonWithType(json: String): T? =
fromJson<T>(json, object : TypeToken<T>() {}.type)
I created a test module, test-utils, to be used in other modules to prevent same boilerplate code.
The issue i saw examining the other projects i saw you don't add dependencies to this module using testImplementation or androidTestImplementation, instead you put files to main folder instead of test-shared folder, and use implementation and add this module to other modules using testImplementation(project("..")), if you use testImplementation instead of implementation you get unresolved reference error from tests, for instance in data module.
Dependencies in test-utils module build.gradle.kts
dependencies {
implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
implementation(Deps.KOTLIN)
implementation(Deps.ANDROIDX_CORE_KTX)
implementation(Deps.RX_JAVA)
implementation(Deps.RX_ANDRIOD)
implementation(Deps.COROUTINES_CORE)
implementation(Deps.COROUTINES_ANDROID)
implementation(TestDeps.ANDROIDX_CORE_KTX)
implementation(TestDeps.ANDROIDX_CORE_TESTING)
implementation(Deps.GSON)
}
Add test-utils module as project to data module with
testImplementation(project(Modules.AndroidLibrary.TEST_UTILS))
However, with this approach i cannot read from the json file located in resources folder inside test folder and get null pointer exception. Also, can't use assets folder either since this file is required in unit tests? Is there anyway to add json file without putting it inside resources folder in every module?