Hi All Is there any way to use Android Context in ...
# multiplatform
h
Hi All Is there any way to use Android Context in the KMM test?
h
Hey! You can access it in
androidTest
source and it has to be instrumentation test as far as I understand. https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests
h
I have an expect/actual function in commonMain that I'm using the Android context in the Android part. And now when I write a unit test for this function, the context is always null. So you mean I have to write the test in the androidTest to get the context using androidx.test or robolectric? 🤔 Isn't there any more convenient way?
h
I’m doing more or less the same. Why is it inconvenient?
Context
is android specific and it’s only available when the app runs, so you need to emulate that behavior to test the code where it is used
h
Because instead of writing one test in the commonTest I have to wirte two tests for one function, one in androidTest and another in iosTest. Also because if I write the unit test in the commonTest it always fails when I run it on Android, I cannot write it in the commonTest at all
h
You have 2 different functions and each one of them requires a certain runtime. If you need to test logic independent of that, you could try separating it into the commonMain and test once. But if your function needs to read from assets or in any other way do something that is only available in an Android/iOS runtime, I don’t really see how a common test run on JVM could cover it
g
You could define a `expect`KContext in commonMain, in androidMain a typealias to android.Context and nothing for other platforms, so that you have 1 UT. It also means that you'll pass a KContext everywhere you want an Android context and it'll mean nothing for other platforms.

https://youtu.be/yCLI_dIx660?t=259â–ľ

1251 Views