3

From here we now know that robolectric does not have a shadow object but we can create a custom shadow object for a snackbar.It's ashame they have one for toast but not for snackbar.

I am showing a snackbar in my code when there is no network connection. I'd like to know how can i write a unit test (with robolectric as the test runner) that can verify that a snackbar gets shown when there is no network connection.

Its a little hard because the snackbar is not in xml. So when i declare my actually Activity controller it doesn't have a snackbar at that time.

You know how to test a toast we have ShadowToast.getTextOfLatestToast() i want one for snackBar

im currently using org.robolectric:robolectric:3.0-rc2 and dont see ShadowSnackbar.class available.

4

2 回答 2

3

实际上在博文中解释了如何添加 ShadowToast 类来启用测试。

  1. 将 ShadowSnackbar 添加到您的测试源中;
  2. 在您的自定义 Gradle 测试运行器中添加 Snackbar 类作为检测类;
  3. 在您的测试中添加 ShadowSnackbar 作为阴影;

在您的应用程序代码中,当没有可用的互联网连接时,您将调用 Snackbar。由于将 Snackbar 配置(例如拦截)作为 Instrumented 类,将使用该类的 Shadow-variant。届时您将能够评估结果。

于 2015-11-30T14:14:20.397 回答
2

我发布了一个更简单的答案

你可以这样做:

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
}
于 2018-06-14T14:58:59.570 回答