android-test icon indicating copy to clipboard operation
android-test copied to clipboard

ServiceTestRule not support the Service whicha runs in a separat process

Open Leojangh opened this issue 8 months ago • 0 comments

I'm writing the unit tests for MyService, which runs in a separate process android:process=":ai", and the code like this:

//The Service:
class MyService: Service() {
    inner class TestBinder() : Binder() { 
        fun getService() = this@MyService
    }

    override fun onBind(intent: Intent?): IBinder? {
        return TestBinder()
    }
}
//The test:
@RunWith(AndroidJUnit4::class)
internal class MyServiceTest { 

    private val rule = ServiceTestRule()

    @Test
    fun test() {
        val binder = rule.bindService(Intent(ApplicationProvider.getApplicationContext(), MyService::class.java))
        val service = (binder as MyService.TestBinder).getService() 
    }
}

But ClassCastException was thrown: java.lang.ClassCastException: android.os.BinderProxy cannot be cast to MyService$TestBinder

But test works if I make MyService without separate process.

Leojangh avatar Jun 13 '25 06:06 Leojangh