在Android Studio中进行单元测试和UI测试 - 7.为app添加简单的交互

系列教程

在使用Espresso进行UI测试前,让我们为app添加一些Views和简单的交互。我们使用一个用户可以输入名字的EditText,欢迎用户的Button和用于输出的TextView。打开res/layout/activity_main.xml,粘贴如下代码:
activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:hint="Enter your name here"
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Say hello!"
        android:layout_below="@+id/editText"
        android:onClick="sayHello"/>
</RelativeLayout>

还需要在MainActivity.java中添加onClick handler:

MainActivity.java

public void sayHello(View v){
    TextView textView = (TextView) findViewById(R.id.textView);
    EditText editText = (EditText) findViewById(R.id.editText);
    textView.setText("Hello, " + editText.getText().toString() + "!");
}

现在可以运行app并确认一切工作正常。在点击Run按钮之前,确认你的Run Configuration没有设置为运行测试。如需更改,点击下拉选项,选择app

下一篇:在Android Studio中进行单元测试和UI测试 - 8.创建并运行Espresso测试

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,046评论 25 709
  • 本篇教程翻译自Google I/O 2015中关于测试的codelab,掌握科学上网的同学请点击这里阅读:Unit...
    TestDevTalk阅读 141,156评论 55 485
  • 本文章转载于搜狗测试 本文转自简书,是作者翻译Google I/0 2015中关于测试的codelab。 目录 1...
    夜境阅读 4,929评论 1 0
  • 作为一个大学新生,终于让我有些时间去阅读一些有意义的书籍,而我选择的第一本书就是卡勒德,胡塞尼的《追风筝的人》,显...
    JKCP阅读 2,361评论 4 7
  • 距离我上一次完完整整地看完一部古装,已经好久远,久远到不是仙剑1就是还珠2。 口碑这东西真的好用,难怪现在商业里...
    阿又又人余阅读 2,532评论 0 0