美文网首页
Android测试之Espresso

Android测试之Espresso

作者: 卖梦想的男孩 | 来源:发表于2017-02-21 15:43 被阅读85次

    Espresso 测试框架提供了一组 API 来构建 UI 测试,用于测试应用中的用户流,可以编写简洁、运行可靠的自动化 UI 测试,适合编写白盒自动化测试,新版的AS已经能够支持自动录制测试脚本,再配合适当的修改可能更方便快捷的写出测试用例。
    要求 Android 2.2(API >= 8)。

    配置是在JUnit的基础上引入Espresso库

    dependencies{
     androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
    }
    

    查找元素:

    • 视图的类名称
    • 视图的内容描述
    • 视图的 R.id
    • 视图中显示的文本

    支持的操作:

    • 视图点击
    • 滑动
    • 按下按键和按钮
    • 键入文本
    • 打开链接

    详情Api见:传送门

    package cn.kerison.playground.main;
    // import ...;
    @RunWith(AndroidJUnit4.class)
    @LargeTest
    public class DemoActivityTest {
    
        @Rule
        public ActivityTestRule<DemoActivity> mActivityRule = new ActivityTestRule<>(
                DemoActivity.class);
    
        @Before
        public void setUp() throws Exception {
            System.out.println("call setUp in test");
        }
    
        @After
        public void tearDown() throws Exception {
            System.out.println("call tearDown in test");
        }
    
        @Test
        public void sayHello() throws Exception {
            System.out.println("call sayHello in test");
            mActivityRule.getActivity().sayHello();
        }
    
        @Test
        public void clickFAB() throws Exception{
            System.out.println("call clickFB in test");
            onView(withId(R.id.fab)).check(matches(isClickable()));
            onView(withId(R.id.fab)).perform(click()).check(matches(isDisplayed()));
        }
    
        @Test
        public void inputText() throws  Exception{
            System.out.println("call inputText in test");
            onView(withId(R.id.input_view)).perform(typeText("abcd"), closeSoftKeyboard());
        }
    }
    

    这里的typeText不支持中文,如果需要中文,其实采用replaceText更快,这里是为了查看输入过程。
    Espresso还支持WebView,更多可以查看这里

    附录

    虽然api已经简化的不少,但是人都是怕麻烦的,当然是越简单越好。
    AS提供了测试录制功能。
    点击Run -> Recording Espresso Test。
    会让你选择启动设备让你输入需要操作的步骤。设备启动后直接操作你需要的步骤就可以了,列表里会自动显示你操作过的步骤,你还可以手动添加Assertion,当然录制也不是那么完美,最起码已经能支持的比手写的快了不少。最后点击Complete Recording即可生成相应的测试用用例。


    录制测试脚本

    相关文章

      网友评论

          本文标题:Android测试之Espresso

          本文链接:https://www.haomeiwen.com/subject/zphuwttx.html