从这里中,我们现在知道robolectric没有影子对象,但是我们可以为snackbar创建一个自定义的影子对象,这是因为他们有一个用于吐司的,而不是用来做零食的。
当没有网络连接时,我在代码中显示一个快捷键。我想知道如何编写单元测试(使用robolectric作为测试运行程序),以验证在没有网络连接时是否显示了snackbar。
这有点困难,因为snackbar不在xml中。所以当我声明我的实际活动控制器时,它当时没有零食条。
你知道如何测试吐司,我们有ShadowToast.getTextOfLatestToast(),我想要一杯给snackBar
我目前正在使用org.robolecture:robolectric:3.0-Rc2,并且看不到ShadowSnackbar.class可用。
发布于 2015-11-30 14:14:20
博客文章中实际上解释了如何添加ShadowToast类来启用测试。
在应用程序的代码中,当没有互联网连接时,您将调用Snackbar。由于配置(例如截取)将Snackbar作为仪表类,将使用该类的Shadow变体。你可以在那一刻对结果进行评估。
发布于 2018-06-14 14:58:59
我发了很多简单答案
你可以这样做:
val textView: TextView = rootView.findSnackbarTextView() assertThat(textView,
is(notNullValue()
执行情况:
/**
* @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
}发布于 2022-11-19 22:10:47
这是对我有用的,但它是一个非常简单的用例。
@Implements(Snackbar::class)
class CustomShadowSnackbar {
companion object {
val shownSnackbars = mutableListOf<Snackbar>()
fun Snackbar.getTextMessage(): String {
val view = (this.view as ViewGroup)
.children
.first { it is SnackbarContentLayout } as SnackbarContentLayout
return view.messageView.text.toString()
}
fun clear() {
shownSnackbars.clear()
}
}
@RealObject
lateinit var snackbar: Snackbar
@Implementation
fun show() {
shownSnackbars.add(snackbar)
}
@Implementation
fun __constructor__(
context: Context,
parent: ViewGroup,
content: View,
contentViewCallback: ContentViewCallback) {
Shadow.invokeConstructor(
Snackbar::class.java,
snackbar,
ReflectionHelpers.ClassParameter(Context::class.java, context),
ReflectionHelpers.ClassParameter(ViewGroup::class.java, parent),
ReflectionHelpers.ClassParameter(View::class.java, content),
ReflectionHelpers.ClassParameter(ContentViewCallback::class.java, contentViewCallback)
)
}
}https://stackoverflow.com/questions/33421913
复制相似问题