代码之家  ›  专栏  ›  技术社区  ›  NSaran

带有ServiceTestRule的bindService方法的ClassCastException

  •  1
  • NSaran  · 技术社区  · 9 年前

    我编写了一个使用ServiceTestRule获取绑定服务的函数,如下所示:

    class Parent {
        companion object {
            fun <T : AbstractUIService> getBoundService(clazz: Class<T>): T {
                var binder: IBinder? = null
                while (binder == null) {
                    binder = serviceTestRule.bindService(
                        Intent(InstrumentationRegistry.getTargetContext().applicationContext, clazz))
                }
                return (binder as LocalBinder<T>).service
            }
        }
    }
    

    class ChildATests: Parent() {
        companion object {
            lateinit var serviceA: ServiceA
    
            @BeforeClass @JvmStatic
            fun setUp() {
                serviceA = getBoundService(ServiceA::class.java)
            }
        }
    }
    

    如果我只需要运行一个Child*Tests类,这很好。但当我运行整个套件时,第一个类运行良好,但其余类失败,出现以下错误:

    Java语言lang.ClassCastException:ServiceB不能转换为ServiceA

    如果需要更多细节来澄清情况,请告诉我。

    1 回复  |  直到 9 年前
        1
  •  1
  •   NSaran    9 年前

    这个问题的解决方案是将ServiceConnection适配器与ServiceTestRule的bindService方法一起使用。因此,我的getBoundService函数现在如下所示:

    fun <T : AbstractUIService> getBoundService(clazz: Class<T>): T {
        val serviceConnectionAdapter = doOperationWithLatch {
            val adapter = ServiceConnectionAdapter(it)
            serviceTestRule.bindService(
                    Intent(InstrumentationRegistry.getTargetContext().applicationContext, clazz),
                    adapter,
                    Context.BIND_AUTO_CREATE
            )
            adapter
        } as ServiceConnectionAdapter
    
        return (serviceConnectionAdapter.service as LocalBinder<T>).service
    }
    

    哪里 it