无法在 Robolectric 测试用例中的自定义视图上使用 perform click()?

Unable to use performclick() on customview in Roboelectric testcase?

我的 xml

中有如下自定义视图
                   <com.examle.RowPhoto
                    android:id="@+id/agent_floating_row"
                    android:layout_marginStart="@dimen/size_16dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:visibility="gone"
                    app:cardElevation="@dimen/size_0dp" />

Class 同样是

class RowPhoto(context: Context, attributeSet: AttributeSet?) : CardView(context, attributeSet){
private var rowClick: RowEventCallback? = null
private var mRowConfig: FloatingRowConfig? = null
private lateinit var mRowEnum: FloatingRowEnum


init {

    LayoutInflater.from(context).inflate(R.layout.row_photo, this, true)


   RowPhotoVariationId.setOnClickListener {
        rowClick?.onRowclick()
    }
}

fun setOnRowClickListener(rowClick: RowEventCallback) {
    this.rowClick = rowClick
}

无法更改上面的任何内容 class 因为它是许多 activities/fragments.

中使用的可重用组件

在我的测试class 中,我想在整个视图上使用 performclick()。 我的测试Class 如下所示。

@Config(sdk = [ Build.VERSION_CODES.P])
@RunWith(RobolectricTestRunner::class)
class ActvityTest{
    private lateinit var activity: Activity
    private lateinit var myCustomView: RowPhoto
    @Before
    fun setUp(){
        activity = Robolectric.buildActivity(Activity::class.java).create().resume().get()
        val attributeSet = with(Robolectric.buildAttributeSet()) {
            build()
        }

        myCustomView = RowPhoto(activity, attributeSet)
    }

    @Test
    fun test_activity_not_null(){
        assertNotNull(activity)
    }




    @Test
    fun checkNavigation(){
        // myCustomView.performClick()
        // activity.findViewById<View>(R.id.agent_floating_row).performClick()
        myCustomView.performClick()
    }
}

活动中的点击监听器和导航方法是这样的

private fun setOnCLickListener() {
    agent_floating_row.setOnRowClickListener(object : RowEventCallback {
        override fun onRowclick() {
            navigationdActivity()
        }
    })
}
fun navigationdActivity() {
    val intent = Intent(this@Activity,MyHero::class.java)
    startActivity(intent)
}

但是 Performclick() 没有触发,控件没有进入 setOnCLickListener() 函数。有帮助吗?

可以使用反射访问自定义视图的私有字段private var rowClick: RowEventCallback? = null,然后在测试中调用点击接口

所以测试应该看起来像这样

@Test
fun checkNavigation(){
    val myCustomView = activity.agent_floating_row
    val eventListener = RowPhoto::class.java.getDeclaredField("rowClick")
    eventListener.isAccessible = true

    val clickInterface = eventListener.get(myCustomView) as RowEventCallback
    clickInterface.onRowclick()
}