Robolectric 测试以检查是否显示 SnackBar? [英] Robolectric test to check if a SnackBar is shown?
本文介绍了Robolectric 测试以检查是否显示 SnackBar?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的应用中调用以下代码:
I am calling the following code in my app:
Snackbar.make(this, R.string.empty_task_message, Snackbar.LENGTH_LONG)
.show()
在我的 Robolectric 测试中,我如何断言这确实被调用了?
How can I assert that this was indeed called, inside my Robolectric test?
我正在考虑诸如遍历视图层次结构并搜索 Snackbar
实例并检查视图是否可见之类的事情.
I was thinking of something like traversing the view hierarchy and searching for a Snackbar
instance and checking if the view is visible.
这看起来像是 Robolectric 中长期存在的问题.
This looks like a long standing problem in Robolectric.
推荐答案
与其创建 ShadowClass
相比,我发现了一个更好(更简单、更简单)的方法:
Rather than creating a ShadowClass
I found a much better (simpler and less hacky) way:
/**
* @return a TextView if a snackbar is shown anywhere in the view hierarchy.
*
* NOTE: calling Snackbar.make() does not create a snackbar. Only calling #show() will create it.
*
* If the textView is not-null you can check its text.
*/
fun View.findSnackbarTextView(): TextView? {
val possibleSnackbarContentLayout = findSnackbarLayout()?.getChildAt(0) as? SnackbarContentLayout
return possibleSnackbarContentLayout
?.getChildAt(0) as? TextView
}
private fun View.findSnackbarLayout(): Snackbar.SnackbarLayout? {
when (this) {
is Snackbar.SnackbarLayout -> return this
!is ViewGroup -> return null
}
// otherwise traverse the children
// the compiler needs an explicit assert that `this` is an instance of ViewGroup
this as ViewGroup
(0 until childCount).forEach { i ->
val possibleSnackbarLayout = getChildAt(i).findSnackbarLayout()
if (possibleSnackbarLayout != null) return possibleSnackbarLayout
}
return null
}
用作:
val textView: TextView? = rootView.findSnackbarTextView()
assertThat(textView, `is`(notNullValue()))
上面的代码是kotlin的,你可以用java来实现
The above code is kotlin, you can implement the same in java
这篇关于Robolectric 测试以检查是否显示 SnackBar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文