TextView中的Espresso文本与所选视图不匹配

15

我在使用Espresso进行测试时遇到了一个奇怪的失败。以下是测试显示Dialog中的TextView。我收到以下错误:

   com.google.android.apps.common.testing.ui.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with string from resource id: <2131099772>' doesn't match the selected view.
Expected: with string from resource id: <2131099772>[my_content] value: Test Content Available
Got: "TextView{id=2131296340, res-name=dialog_content, visibility=VISIBLE, width=620, height=38, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=Test Content Available, input-type=0, ime-target=false}"

at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:579)
at com.google.android.apps.common.testing.ui.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:69)
at com.google.android.apps.common.testing.ui.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:40)
at com.google.android.apps.common.testing.ui.espresso.ViewInteraction.runSynchronouslyOnUiThread(ViewInteraction.java:159)
at com.google.android.apps.common.testing.ui.espresso.ViewInteraction.check(ViewInteraction.java:133)
at com.myapp.testContentDetails(FPATest.java:109)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:192)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner.onStart(GoogleInstrumentationTestRunner.java:167)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1701)
Caused by: junit.framework.AssertionFailedError: 'with string from resource id: <2131099772>' doesn't match the selected view.
Expected: with string from resource id: <2131099772>[my_content] value: Test Content Available
Got: "TextView{id=2131296340, res-name=dialog_content, visibility=VISIBLE, width=620, height=38, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=Test Content Available, input-type=0, ime-target=false}"

at com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.assertThat(ViewMatchers.java:789)
at com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions$2.check(ViewAssertions.java:76)
at com.google.android.apps.common.testing.ui.espresso.ViewInteraction$2.run(ViewInteraction.java:145)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5081)
at java.lang.reflect.Method.invokeNative(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)

很明显,视图已找到,在其详细信息中,您可以看到text=我期望的值。然而,它说不匹配。它是在以下测试语句下运行的:

onView(withId(R.id.dialog_content)).check(
                matches(withText(R.string.my_content)));

我也尝试使用下面的语句,但是出现了NoMatchingViewException错误,尽管该视图在异常的视图层次结构中显示。
onView(withText(R.string.my_content)).check(
                matches(isDisplayed()));

任何关于为什么会失败的帮助?值得注意的是,我可以在对话框中的兄弟字段上使用withText() isDisplayed()。

14
Espresso 自带的 withText(int resourceId) 功能存在缺陷。它只能检查 java.lang.String 类型的文本,但很多使用的文本实际上是 CharSequence 的其他子类,比如 Editable 或 Spannable。一定要确保你要比较的文本类型是 String,如果不是,则需要编写自己的匹配器,以在不考虑类型的情况下匹配字符串内容。 - haffax
@haffax 太好了!我已经使用Html.fromHtml()在TextView中设置了文本,这当然会导致一个Spanned对象。编写了一个自定义匹配器,在#matchesSafely()中只是对textView.getText()进行了#toString(),它完美地工作了。如果你想把这个作为答案提交,我会标记它为已接受的,谢谢! - JCricket
在我的情况下,我需要跟屏幕上的全大写文本进行匹配。真正的字符串是小写的,并且设置了 allCaps 属性,所以我必须用小写来匹配。 - JoKr
1个回答

8

这个答案是基于 @haffax 的评论创建的。

/**
 * Original source from Espresso library, modified to handle spanned fields
 * 
 * Returns a matcher that matches a descendant of {@link TextView} that is
 * displaying the string associated with the given resource id.
 * 
 * @param resourceId
 *            the string resource the text view is expected to hold.
 */
public static Matcher<View> withText(final int resourceId) {

    return new BoundedMatcher<View, TextView>(TextView.class) {
        private String resourceName = null;
        private String expectedText = null;

        @Override
        public void describeTo(Description description) {
            description.appendText("with string from resource id: ");
            description.appendValue(resourceId);
            if (null != this.resourceName) {
                description.appendText("[");
                description.appendText(this.resourceName);
                description.appendText("]");
            }
            if (null != this.expectedText) {
                description.appendText(" value: ");
                description.appendText(this.expectedText);
            }
        }

        @Override
        public boolean matchesSafely(TextView textView) {
            if (null == this.expectedText) {
                try {
                    this.expectedText = textView.getResources().getString(
                            resourceId);
                    this.resourceName = textView.getResources()
                            .getResourceEntryName(resourceId);
                } catch (Resources.NotFoundException ignored) {
                    /*
                     * view could be from a context unaware of the resource
                     * id.
                     */
                }
            }
            if (null != this.expectedText) {
                return this.expectedText.equals(textView.getText()
                        .toString());
            } else {
                return false;
            }
        }
    };
}

我希望我能给它点赞两次。 - Plinio.Santos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接