Android UI自动化测试--Espresso

本文介绍如何使用Espresso进行Android UI自动化测试,包括Gradle配置、测试类编写及常见测试方法,如视图验证和交互操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.gradle配置

加入以下库:

androidTestCompile 'com.android.support.test:runner:0.+'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.+'
androidTestCompile 'com.android.support:support-annotations:23+'

在defaultconfig下加入:

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
用于指定这个类来解析和执行所有测试用例


2.测试类:

package com.example.zhouyi.unittest;

import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;


/**
 * Created by zhouyi on 16/7/19.
 */

@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    @Rule
    public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule<>(
            MainActivity.class);




    @Test
    public void have_view_text_add() {
        onView(withId(R.id.btntest))
                .check(matches(withText("add")));

    }

}

测试类前面加上RunWith注解

一个测试类可以测试多个activity,这个测试类中需要测试哪些activity,就要配置多少个对应的activityrule

onView方法设置需要观察的view,这个view可以由withid(以id索引)或withtext(以内容查找)来指定

check:指定按什么规则来检测view,比如上例中检测button里的文字是否是add


注意:要执行的测试方法中测试的activity必须启动才能测试,比如上例中,执行have_view_test_add,要btntest所在的mainactivity启动才行


其他测试方法还有:

所有text为add的view中,有一个显示出来的

onView(withText("add")).check(matches(isDisplayed()));

edttest对应的edittext执行三部操作:清空,写入字符串qf,关闭软键盘,然后点击btntest对应的按钮,最后判断edittext里面的内容是否为qfok

onView(ViewMatchers.withId(R.id.edttest)).perform(clearText(),typeText("qf"), ViewActions.closeSoftKeyboard());
onView(ViewMatchers.withId(R.id.btntest)).perform(click());
onView(ViewMatchers.withId(R.id.edttest)).check(matches(withText("qfok")));

其他测试方法可以参考github:

https://github.com/chiuki/espresso-samples





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值