Android 测试快速入门必看,你要知道的都在这了!

在正式学习Android应用测试之前,我们先来了解以下几个概念。

JUnit

JUnit是一个Java语言的单元测试框架。

Instrumentation

该框架基于JUnit,因此既可以直接使用Junit 进行测试。又其为Android 应用的每种组件提供了测试基类,因此也可以使用Instrumentation 来测试Android 组件。

Instrumentation和Activity有点类似,只不过Activity是需要一个界面的,而Instrumentation并不是这样的,我们可以将它理解为一种没有图形界面的,具有启动能力的,用于监控其他类(用Target Package声明)的工具类。

Espresso

自动化测试使用Android的Instrumentation API,这些API的调用在一个与UI线程不同的线程中运行,因此,使用自动化方法测试用户界面会导致严重的并发问题,进而产生不一致不可靠的测试结果。Google对这个问题的解决方案是Espresso,它是一个测试框架,能够使UI测试在多线程环境中安全地运行,并移除了关于编写测试的大部分样板代码

测试应用

AndroidJUnit基于JUnit,使得我们既可以在JVM上运行本地单元测试(local unit tests),也可以在Android设备上进行仪器测试(instrumented tests)。测试代码的位置取决于您要编写的测试的类型。 Android Studio 为以下两种测试类型提供了源代码目录(源集):

本地单元测试

  • 位于 module-name/src/test/java/。
  • 这些测试在计算机的本地 Java 虚拟机 (JVM) 上运行。 当您的测试没有 Android 框架依赖项或当您可以模拟 Android 框架依赖项时,可以利用这些测试来尽量缩短执行时间。
  • 在运行时,这些测试的执行对象是去掉了所有 final 修饰符的修改版 android.jar。 这样一来,您就可以使用 Mockito 之类的常见模拟库。

仪器测试

  • 位于 module-name/src/androidTest/java/。
  • 这些测试在硬件设备或模拟器上运行。 这些测试有权访问 Instrumentation API,让您可以获取某些信息(例如您要测试的应用的 Context), 并且允许您通过测试代码来控制受测应用。 可以在编写集成和功能 UI 测试来自动化用户交互时,或者在测试具有模拟对象无法满足的 Android 依赖项时使用这些测试。
  • 由于仪器测试内置于 APK 中(与您的应用 APK 分离),因此它们必须拥有自己的 AndroidManifest.xml 文件。 不过,由于 Gradle 会自动在构建时生成该文件,因此它在您的项目源集中不可见。 您可以在必要时(例如需要为 minSdkVersion 指定其他值或注册测试专用的运行侦听器时)添加自己的清单文件。 构建应用时,Gradle 会将多个清单文件合并成一个清单。

当您新建项目或添加应用模块时,Android Studio 会创建以上所列的测试源集,并在每个源集中加入一个示例测试文件。您可以在project窗口中看到他们,如图1-1所示:

图1-1

添加一个新测试

在写单元测试之前,务必确定gradle中做好相应的配置。如图1-2所示

图1-2

接下来就正式入门啦,表激动,一步步来会很简单哦~

创建一个本地单元测试

第一步 :打开包含您想测试的代码的 Java 文件。如Calculator.java

/**
 * [description]
 * author: yifei
 * created at 17/6/8 下午12:00
 */
public class Calculator {
    public double sum(double a, double b){
        return a + b;
    }

    public double substract(double a, double b){
        return a - b;
    }

    public double divide(double a, double b){
        return a * b;
    }

    public double multiply(double a, double b){
        return a / b;
    }
}

第二步:点击您想测试的类或方法,然后右击如图2所示,或按 Ctrl+Shift+T (⇧⌘T)。

图2

选择create test如图3所示,并选择setUp/@Before和需要测试的方法,然后点击OK

图3

在 Choose Destination Directory 对话框中,点击与您想创建的测试类型对应的源集:androidTest 对应于仪器测试,test 对应于本地单元测试。然后点击 OK。如图4所示

图4

这时在module-name/src/test/java/下出现了CalculatorTest.java

/**
 * [description]
 * author: yifei
 * created at 17/6/8 下午12:01
 */
public class CalculatorTest {

    private Calculator mCalculator;

    @Before
    public void setUp() throws Exception {
        mCalculator = new Calculator();
    }

    @Test
    public void sum() throws Exception {
        //expected: 6, sum of 1 and 5
        assertEquals(6d, mCalculator.sum(1d, 5d), 0);
    }

    @Test
    public void substract() throws Exception {
        assertEquals(1d, mCalculator.substract(5d, 4d), 0);
    }

    @Test
    public void divide() throws Exception {
        assertEquals(4d, mCalculator.divide(20d, 5d), 0);
    }

    @Test
    public void multiply() throws Exception {
        assertEquals(10d, mCalculator.multiply(2d, 5d), 0);
    }
}

此时选中方法名,右击run’method()’

图5

于是一个本地单元测试就完成啦,是不是比较简单呢。。。

创建一个Espresso测试

在创建测试之前,我们建立一个待测试的TestActivity.java,添加一下简单的交互。在EditText中输入任意字符串,点击Button在TextView中显示出来,如图6、7所示

图6

图7

为了照顾到更多小伙伴,这里尽量写的细点,对应的Activity/xml文件如下所示:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class TestActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView textView;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        init();
    }

    public void init(){
        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);
        findViewById(R.id.btnText).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btnText) {
            textView.setText("Hello, " + editText.getText().toString() + "!");
        }
    }
}

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.testing.androidtest.TestActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <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:id="@+id/btnText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Hello world!"
            android:layout_below="@+id/editText"/>

    </RelativeLayout>

</android.support.design.widget.CoordinatorLayout>

做完以上工作后,我们一起来创建并运行Espresso测试。在module-name/src/androidTest/java/下创建TestActivityInstrumentationTest.java

import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;

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.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
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;

/**
 * [description]
 * author: yifei
 * created at 17/6/8 下午12:31
 */
@RunWith(AndroidJUnit4.class)
@LargeTest
public class TestActivityInstrumentationTest {

    private static final String STRING_TO_BE_TYPED = "Peter";

    @Rule
    public ActivityTestRule<TestActivity> mActivityRule = new ActivityTestRule<>(TestActivity.class);

    @Test
    public void sayHello(){
        onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()); //line 1

        onView(withText("Hello world!")).perform(click()); //line 2

        String expectedText = "Hello, " + STRING_TO_BE_TYPED + "!";
        onView(withId(R.id.textView)).check(matches(withText(expectedText))); //line 3
    }
}

测试类通过AndroidJUnitRunner运行,并执行button的onClick(View)方法。下面将逐行解释都做了什么:

1.首先,找到ID为editText的view,输入Peter,然后关闭键盘;
2.接下来,点击Hello world!的View,我们既可以使用ID来找到一个控件,还可以通过搜索它上面的文字来找到它;
3.最后,将TextView上的文本同预期结果对比,如果一致则测试通过;

你也可以右键点击域名运行测试,选择Run> TestActivityInstrumentationTest…如图8所示:

图8

这样就会在模拟器或者连接的设备上运行测试,你可以在手机屏幕上看到被执行的动作(比如在EditText上打字)如下视频所示。

录屏

最后会在Android Studio输出通过和失败的测试结果。

图9

最后恭喜你,你也入门了。。。

最后

在这里我总结出了互联网公司Android程序员面试简历模板,面试涉及到的绝大部分面试题及答案做成了文档和架构视频资料免费分享给大家【包括高级UI、性能优化、架构师课程、NDK、Kotlin、混合式开发(ReactNative+Weex)、Flutter等架构技术资料】,希望能帮助到您面试前的复习且找到一个好的工作,也节省大家在网上搜索资料的时间来学习。

资料获取方式:加入Android架构交流QQ群聊:513088520 ,进群即领取资料!!!

点击链接加入群聊【Android移动架构总群】:加入群聊

资料大全

猜你喜欢

转载自blog.csdn.net/weixin_43351655/article/details/88541068