无法在Roboelectric测试用例中对customview使用performclick()



我的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 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
}

不能更改上面类中的任何内容,因为它是跨许多活动/片段使用的可重用组件。

在我的测试类中,我想在整个评审中使用performclick((。我的TestClass如下所示。

@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)
}

但是Performlick((没有触发,控件没有进入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()
}

最新更新