I'm having an issue unit testing an android compon...
# android
r
I'm having an issue unit testing an android component. I have the following code:
Copy code
val fileUrl = requireNotNull(
  javaClass.classLoader?.getResource("test.csv")
)
val newFile = File(fileUrl.toURI())
To load a file from resources to use during my test The issue I'm having is that this
getResource()
call only works the first time, and subsequent executions of the code getting that resource fails. If I re-build the project, I can run it again but it will fail subsequent calls. Am I using getResource incorrectly? I have other ways of creating the file, like using copy or writing the actual text to the test file, but I'm confused as to why it's not idempotent
not kotlin but kotlin colored 2
g
what is javaClass in your case?
r
It's the Kotlin JVM Class mapper from Kotlin 1.9.10 So it seems like it's accessing the underlying Java VM. I'm pretty sure we've defined Java 11 in our gradle files as the runtime.
Gave up on this. the Android Studio debugger doesn't properly step into the internals of the call to properly debug this. so instead I ended up re-writing the unit test to create the file like this
Copy code
val newFile = File("test.csv")
newFile.writeText("file content")
Also removed the file from the resources module.
g
I understand what is
javaClass
I meant what is T, from which class you are getting classloader
Never had the issue when resource returned `only once
What is you problem, it returns null from getResource?
r
Seems like that was the case, Both on Android Studio and also while running the unit tests through gradlew. While I was debugging the issue the class loader seemed to be running through a robolectric dependency (SandboxClassLoader implementation?) instead of the java ClassLoader implementation class. So I think it may have been related to that. The URL being returned the first time was a local file path. (e.g. "file:/user/rodrigo/repos/myapp/app/test/resources/test.csv") as opposed to a jar class URI, like an absolute path starting with "/". The subsequent call, just returns null. Also the behavior is not consistent, sometimes I can get two successful runs and the third one will fail. Just frustrating.
g
In general for apps you shouldn't use resources, but use Assets instead, not sure how Robolectic works in this case, but for Android assets look as the correct way, it should work for unit and instrumentation tests