创建自定义的Espresso匹配器

本篇讲述通过BoundedMatcher 自定义了Espresso的匹配器.

概述

Android 提供了 BoundedMatcher 类用来创建针对特定 View 的 Espresso 匹配器.

详细内容请移步 : https://developer.android.com/training/testing/espresso/lists.html

示例

下面是一个关于检查 EditText hint 文本的自定义匹配器:

首先你需要在 src/androidTest/java 目录下创建 Matchers 类.

/**
 * Created by lulu on 2018/3/10.
 * 自定义的 View 匹配器
 */
public class Matchers {
    public static Matcher<View> withItemHint(final String itemHintText) {
        checkArgument(!(itemHintText.equals(null)));
        return withItemHint(is(itemHintText));
    }
    public static Matcher<View> withItemHint(final Matcher<String> matcherText) {
        // 如果传入非法的 matcher 需提前处理
        checkNotNull(matcherText);
        return new BoundedMatcher<View, EditText>(EditText.class) {

            @Override
            public void describeTo(Description description) {
                description.appendText("该 EditText 的 Hint 为: " + matcherText);
            }

            @Override
            protected boolean matchesSafely(EditText item) {
                return matcherText.matches(item.getHint().toString());
            }
        };
    }
}

通过下面代码使用你刚才创建 Matchers 类.

// more
import static com.lulu.androidtestdemo.espresso.custom_matcher.Matchers.withItemHint;

/**
 * Created by lulu on 2018/3/10.
 * 测试自定义匹配器
 */
@RunWith(AndroidJUnit4.class)
public class TestCustomMatcher {

    @Rule
    public ActivityTestRule<EspressoTest1Activity> mRule =
            new ActivityTestRule<EspressoTest1Activity>(EspressoTest1Activity.class);

    @Test
    public void testEditHintDisplay() throws Exception {
        onView(withId(R.id.inputField)).check(matches(withItemHint("this is a hint")));
    }
}

敲行代码再睡觉

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值