开发者联盟Android知识程序员

Android 测试快速入门

2017-06-08  本文已影响206人  iyifei

在正式学习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 为以下两种测试类型提供了源代码目录(源集):

本地单元测试

仪器测试

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

图1-1.png

添加一个新测试

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

图1-2.png

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

创建一个本地单元测试

第一步 :打开包含您想测试的代码的 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.png
选择create test如图3所示,并选择setUp/@Before和需要测试的方法,然后点击OK
图3.png
在 Choose Destination Directory 对话框中,点击与您想创建的测试类型对应的源集:androidTest 对应于仪器测试,test 对应于本地单元测试。然后点击 OK。如图4所示
图4.png
这时在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.png

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

创建一个Espresso测试

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

图6.png
图7.png
为了照顾到更多小伙伴,这里尽量写的细点,对应的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.png

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


录屏.gif
最后会在Android Studio输出通过和失败的测试结果。
图9.png

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

参考

https://developer.android.com/training/testing/index.html#start
https://developer.android.com/training/testing/start/index.html

上一篇 下一篇

猜你喜欢

热点阅读