android snackbar-如何使用roboelectric进行测试
从现在起,我们知道robolectric没有阴影对象,但我们可以为snackbar创建自定义阴影对象。他们有一个用于toast的阴影对象,但不用于snackbar 当没有网络连接时,我在代码中显示一个snackbar。我想知道如何编写一个单元测试(使用robolectric作为测试运行程序),以验证在没有网络连接时是否显示snackbar 这有点难,因为snackbar不是xml格式的。所以当我声明我的活动控制器时,它当时没有一个snackbar 你知道如何测试一个土司吗?我们有android snackbar-如何使用roboelectric进行测试,android,robolectric,android-snackbar,Android,Robolectric,Android Snackbar,从现在起,我们知道robolectric没有阴影对象,但我们可以为snackbar创建自定义阴影对象。他们有一个用于toast的阴影对象,但不用于snackbar 当没有网络连接时,我在代码中显示一个snackbar。我想知道如何编写一个单元测试(使用robolectric作为测试运行程序),以验证在没有网络连接时是否显示snackbar 这有点难,因为snackbar不是xml格式的。所以当我声明我的活动控制器时,它当时没有一个snackbar 你知道如何测试一个土司吗?我们有ShadowTo
ShadowToast.getTemplatestToast()
snackBar需要一个
我现在正在使用org.roblectric:roblectric:3.0-rc2,看不到ShadowSnackbar.class可用 博客帖子中实际上解释了如何添加ShadowToast类以启用测试
/**
* @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
}
我相信这不是robolectric的一部分,它是另一个开发者解释了如何做到的,对吗?事实上,它不是robolectric的一部分,它可能不会被包括在内,除非有人贡献它。今天,Android及其支持库的发展似乎比Robolectric更快。还有那个“其他开发者”,就是我。
/**
* @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
}