Android Espresso测试withHint不起作用

时间:2017-07-14 15:25:09

标签: android android-espresso android-testing

我目前正在尝试将Espresso UI测试添加到我的Android应用程序中,我希望能够通过它的Hint字段定位TextInputEditText,然后单击它并输入一些文本。 (我知道定位id更好的做法,但我需要在此实例中定位提示)

以下是我尝试这样做的方法:

Espresso.onView(Matchers.allOf(Matchers.instanceOf(TextInputEditText::class.java),
            ViewMatchers.withHint("My Hint"))).
            perform(ViewActions.click(), ViewActions.typeText("type this"))

但是在尝试执行此操作时,我收到以下错误:

  

android.support.test.espresso.NoMatchingViewException:层次结构中找不到匹配的视图:( android.support.design.widget.TextInputEditText的实例,并且提示:是“旧密码”)

即使输出显示层次结构实际上按如下方式保持此视图:

  

TextInputEditText {id = 2131820762,res-name = input_data,visibility = VISIBLE,width = 1328,height = 168,has-focus = true,has-focusable = true,has-window- focus = true,is-clickable = true,is-enabled = true,is-focused = true,is-focusable = true,is-layout-requested = false,is-selected = false,root-is-layout-requested = false,has-input-connection = true,editor-info = [inputType = 0x80091 imeOptions = 0x8000005 privateImeOptions = null actionLabel = null actionId = 0 initialSelStart = 0 initialSelEnd = 0 initialCapsMode = 0x0 hintText = 我的提示 label = null packageName = null fieldId = 0 fieldName = null extras = null hintLocales = null contentMimeTypes = null],x = 0.0,y = 0.0,text =,input-type = 524433,ime-target = true,has-links =假}

ViewMatchers.withHint方法是否在Espresso中被破坏或者是否有特定的方式来使用它?为什么它找不到视图但在输出中实际显示它在层次结构中?

2 个答案:

答案 0 :(得分:1)

此问题已经打开。参见:https://issuetracker.google.com/issues/37139118

答案 1 :(得分:0)

Logcat中的打印可能会产生误导。如果您的TextInputEditTextTextInputLayout的带有提示的子视图,则TextInputLayout将通过TextInputLayout.setHint在内部对其自身设置相同的提示,然后在{{ 1}}为空。

您需要创建一个自定义匹配器来匹配TextInputEditText的提示,作为解决方法:

TextInputEditText

然后将您的fun withHint(title: String): Matcher<View> = withHint(equalTo(title)) fun withHint(matcher: Matcher<String>): Matcher<View> = object : BoundedMatcher<View, TextInputEditText>(TextInputEditText::class.java) { override fun describeTo(description: Description) { description.appendText("with hint: ") matcher.describeTo(description) } override fun matchesSafely(item: TextInputEditText): Boolean { val parent = item.parent.parent return if (parent is TextInputLayout) matcher.matches(parent.hint) else matcher.matches(item.hint) } } 替换为ViewMatchers.withHint("My Hint")