Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Running InstrumentedAndroidTest in KMP project #34

Open
diegocgaona opened this issue Feb 12, 2025 · 0 comments
Open

Running InstrumentedAndroidTest in KMP project #34

diegocgaona opened this issue Feb 12, 2025 · 0 comments

Comments

@diegocgaona
Copy link

Hi, I need some help please,

I want to do some tests using Instrumented in Android (I need to get the appContext, to get the directory to create my test db).
But I was having the error: No instrumentation registered! Must run under a registering instrumentation.

Now, with Kotest, your extension and Roboeletric, I can make Android Studio recognize my class to test as Instrumented test, but now I have the error:
basic:

Invalid test class 'com.diegogaona.cocktailhype.data.repository.TagRepositoryDbTest':
1. No runnable methods
at org.junit.runners.ParentRunner.validate(ParentRunner.java:525)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:92)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:74)

My code is:
My test class in commonTest:

@file:OptIn(ExperimentalCoroutinesApi::class, ExperimentalSerializationApi::class)

package com.diegogaona.cocktailhype.data.repository

import com.diegogaona.cocktailhype.data.local.CouchbaseManager
import com.diegogaona.cocktailhype.data.local.couchbaseLocalConfigTest
import com.diegogaona.cocktailhype.di.LogWrapper
import com.diegogaona.cocktailhype.domain.model.Colors
import com.diegogaona.cocktailhype.domain.model.TagToSave
import com.diegogaona.cocktailhype.domain.model.Translation
import com.diegogaona.cocktailhype.domain.repository.IDatabaseManager
import io.kotest.core.spec.style.FunSpec
import io.kotest.koin.KoinExtension
import kotbase.Database
import kotbase.Collection
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.ExperimentalSerializationApi
import org.junit.runner.RunWith
import org.koin.dsl.module
import org.koin.test.KoinTest
import org.koin.test.inject
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.fail
import org.robolectric.RobolectricTestRunner

val testModule = module {
    val logger = object : LogWrapper {
        override fun d(message: String, tag: String?) {
            println("Debug: $message | Tag: $tag")
        }

        override fun i(message: String, tag: String?) {
            println("Info: $message | Tag: $tag")
        }

        override fun w(message: String, tag: String?) {
            println("W: $message | Tag: $tag")
        }

        override fun e(message: String, tag: String?, throwable: Throwable?) {
            println("Error: $message, Throwable: $throwable")
        }
    }
    single<IDatabaseManager<Database, Collection>> {
        CouchbaseManager(couchbaseLocalConfigTest)
    }
    single<LogWrapper> { logger }
    single<ITagRepository> { TagRepositoryDb(databaseManager = get(), logger = get()) }
}



@RunWith(RobolectricTestRunner::class)
class TagRepositoryDbTest : FunSpec(), KoinTest {
    override fun extensions() = listOf(KoinExtension(testModule))
    val tagRepository by inject<ITagRepository>()
    val databaseManager by inject<IDatabaseManager<Database, Collection>>()

    init {
        test("save and get operations should work correctly") {
            runBlocking {
                val tagToSave = TagToSave(
                    name = Translation(txt = "IntegrationTestTag"),
                    colors = Colors(high = "#FF5733", bg = "#C70039")
                )
                val saveResult = tagRepository.save(tagToSave)
                assertTrue(saveResult.isSuccess, "Tag should be saved successfully.")

                delay(300)

                val tagFlow = tagRepository.getMany("IntegrationTestTag", useFts = false)
                val tags = tagFlow.first()
                assertTrue(
                    tags.isNotEmpty(),
                    "There should be at least one tag matching the search term."
                )

                val savedTag = tags.first() ?: fail("Saved tag should not be null")
                val getResult = tagRepository.get(savedTag.id)
                getResult?.let { assertTrue(it.isSuccess, "get() should return the tag successfully.") }
                val retrievedTag = getResult?.getOrNull() ?: fail("Retrieved tag is null")
                assertEquals(savedTag.id, retrievedTag.id)
                assertEquals("IntegrationTestTag", retrievedTag.name.txt)
            }
        } // More tests....

In my androidInstrumentedTest directory, I have:

package com.diegogaona.cocktailhype

import android.app.Instrumentation
import android.content.Context
import androidx.test.platform.app.InstrumentationRegistry
import br.com.colman.kotest.KotestRunnerAndroid
import org.junit.BeforeClass
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner

lateinit var testAppContext: Context

@RunWith(RobolectricTestRunner::class)
class TestSetup {
    companion object {
        private lateinit var instrumentation: Instrumentation

        @BeforeClass
        @JvmStatic
        fun setupContext() {
            instrumentation = InstrumentationRegistry.getInstrumentation()
            testAppContext = instrumentation.targetContext
        }
    }
}

actual fun getDatabasePathTest(): String {
    TestSetup.setupContext()
    return testAppContext.filesDir.path
}

Why I'm getting this error? Why it doesn't recognize my tests?

Thanks in advance!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant