Android 简明教程

Android - Testing

Android 框架包括一个集成的测试框架,可帮助您测试应用程序的所有方面,而 SDK 工具包含用于设置和运行测试应用程序的工具。无论是使用带 ADT 的 Eclipse 工作还是从命令行工作,SDK 工具均可帮助您在模拟器或目标设备内设置和运行测试。

The Android framework includes an integrated testing framework that helps you test all aspects of your application and the SDK tools include tools for setting up and running test applications. Whether you are working in Eclipse with ADT or working from the command line, the SDK tools help you set up and run your tests within an emulator or the device you are targeting.

Test Structure

Android 的构建和测试工具假设测试项目组织为测试、测试案例类、测试包和测试项目的标准结构。

Android’s build and test tools assume that test projects are organized into a standard structure of tests, test case classes, test packages, and test projects.

android testing1

Testing Tools in android

有很多可用于测试 Android 应用程序的工具。有些是正式工具,如 JUnit 和 Monkey,而另一些是可用于测试 Android 应用程序的第三方工具。在本章中,我们将讲解这两种用于测试 Android 应用程序的工具。

There are many tools that can be used for testing android applications. Some are official like Junit,Monkey and some are third party tools that can be used to test android applications. In this chapter we are going to explain these two tools to test android applications.

  1. JUnit

  2. Monkey

JUnit

您可以使用 JUnit TestCase 类对不调用 Android API 的类执行单元测试。TestCase 也是 AndroidTestCase 的基类,您可以使用它来测试依赖 Android 的对象。除了提供 JUnit 框架外,AndroidTestCase 还提供与 Android 相关的设置、终止和帮助器方法。

You can use the JUnit TestCase class to do unit testing on a class that doesn’t call Android APIs. TestCase is also the base class for AndroidTestCase, which you can use to test Android-dependent objects. Besides providing the JUnit framework, AndroidTestCase offers Android-specific setup, teardown, and helper methods.

为了使用 TestCase,请将您的类扩展为 TestCase 类并实现一个名为 setUp() 的方法调用。其语法如下所示:

In order to use TestCase, extend your class with TestCase class and implement a method call setUp(). Its syntax is given below −

public class MathTest extends TestCase {
   protected double fValue1;
   protected double fValue2;

   protected void setUp() {
      fValue1= 2.0;
      fValue2= 3.0;
   }
}

对于每个测试,实现一个与固定装置交互的方法。使用 assertTrue(String, boolean) 调用一个布尔值来验证预期结果与断言相符。

For each test implement a method which interacts with the fixture. Verify the expected results with assertions specified by calling assertTrue(String, boolean) with a boolean.

public void testAdd() {
   double result= fValue1 + fValue2;
   assertTrue(result == 5.0);
}

assert 方法将您预期从测试中得到的值与实际结果进行比较,如果比较失败,则抛出一个异常。

The assert methods compare values you expect from a test to the actual results and throw an exception if the comparison fails.

在定义方法后,您可以运行它们。其语法如下所示:

Once the methods are defined you can run them. Its syntax is given below −

TestCase test= new MathTest("testAdd");
test.run();

Monkey

UI/应用程序演练器 Monkey(通常称为“monkey”)是一个命令行工具,它向设备发送伪随机序列的按键、触摸和手势。您可以使用 Android 调试桥 (adb) 工具运行它。

The UI/Application Exerciser Monkey, usually called "monkey", is a command-line tool that sends pseudo-random streams of keystrokes, touches, and gestures to a device. You run it with the Android Debug Bridge (adb) tool.

使用它来对您的应用程序进行压力测试并报告遇到的错误。您可以通过每次使用相同的随机数种子运行该工具来重复一系列事件。

You use it to stress-test your application and report back errors that are encountered. You can repeat a stream of events by running the tool each time with the same random number seed.

Monkey features

Monkey 有很多功能,但都可以归纳为以下四类。

Monkey has many features, but it can be all be summed up to these four categories.

  1. Basic configuration options

  2. Operational constraints

  3. Event types and frequencies

  4. Debugging options

Monkey Usage

为了使用 monkey,请打开命令提示符,然后导航到以下目录。

In order to use monkey, open up a command prompt and just navigate to the following directory.

android ->sdk ->platform-tools

进入该目录后,使用 PC 连接您的设备,然后运行以下命令。

Once inside the directory, attach your device with the PC , and run the following command.

adb shell monkey -p your.package.name -v 500

可以将此命令分解为以下步骤。

This command can be broken down into these steps.

  1. adb - Android Debug Bridge. A tool used to connect and sends commands to your Android phone from a desktop or laptop computer.

  2. shell - shell is just an interface on the device that translates our commands to system commands.

  3. monkey - monkey is the testing tool.

  4. v - v stands for verbose method.

  5. 500- it is the frequency conut or the number of events to be sent for testing.

这一点还显示在图 − 中

This is also shown in the figure −

monkey

在上述命令中,您在默认安卓 UI 应用程序上运行 monkey 工具。现在,为了在您的应用程序中运行它,您需要执行以下操作。

In the above command, you run the monkey tool on the default android UI application. Now in order to run it to your application , here what you have to do.

最后,您将完成,如下所示

finally you will get finish as shown bellow

这一点还显示在下面的图中。通过输入该命令,实际上您正在生成 500 个随机事件来进行测试。

This has also been shown in the figure below. By typing this command , you are actually generating 500 random events for testing.

monkey1

Example

下面的示例演示了使用 Testing 的方法。它生成了一个可用于 Monkey 的基本应用程序。

The below example demonstrates the use of Testing. It crates a basic application which can be used for monkey.

要尝试此示例,您需要在实际设备上运行此示例,然后按照开始中说明的 Monkey 步骤进行操作。

To experiment with this example, you need to run this on an actual device and then follow the monkey steps explained in the beginning.

Steps

Description

1

You will useAndroid studio to create an Android application under a package com.tutorialspoint.myapplication.

2

Modify src/MainActivity.java file to add Activity code.

3

Modify layouta XML file res/layout/activity_main.xml add any GUI component if required.

4

Create src/second.java file to add Activity code.

5

Modify layout XML file res/layout/view.xml add any GUI component if required.

6

Run the application and choose a running android device and install the application on it and verify the results.

以下是 MainActivity.java 的内容。

Here is the content of MainActivity.java.

package com.tutorialspoint.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
   Button b1;
   @Override

   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      b1=(Button)findViewById(R.id.button);
   }

   public void button(View v){
      Intent in =new Intent(MainActivity.this,second.class);
      startActivity(in);
   }

}

以下是 second.java 的内容。

Here is the content of second.java.

package com.tutorialspoint.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class second extends Activity{
   @Override

   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.view);
      Button b1=(Button)findViewById(R.id.button2);

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(second.this,"Thanks",Toast.LENGTH_SHORT).show();
         }
      });
   }
}

以下是 activity_main.xml 的内容。

Here is the content of activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="UI Animator Viewer"
      android:id="@+id/textView"
      android:textSize="25sp"
      android:layout_centerHorizontal="true" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_alignRight="@+id/textView"
      android:layout_alignEnd="@+id/textView"
      android:textColor="#ff36ff15"
      android:textIsSelectable="false"
      android:textSize="35dp" />

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button"
      android:onClick="button"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="100dp" />

</RelativeLayout>

以下是 view.xml 的内容

Here is the content of view.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent" android:layout_height="match_parent">

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="button"
      android:id="@+id/button2"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:id="@+id/textView3"
      android:textColor="#ff3aff22"
      android:textSize="35dp"
      android:layout_above="@+id/button2"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="90dp" />

</RelativeLayout>

以下是 Strings.xml 的内容。

Here is the content of Strings.xml.

<resources>
   <string name="app_name">My Application</string>
</resources>

以下是 AndroidManifest.xml 的内容。

Here is the content of AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.tutorialspoint.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>

      <activity android:name=".second"></activity>

   </application>
</manifest>

让我们尝试运行您的 Android Testing 应用程序。我假设您已将实际 Android 移动设备连接到计算机。要从 Android Studio 运行该应用程序,请打开您项目的其中一个活动文件,然后从工具栏中单击“Run”图标。在启动您的应用程序之前,Android Studio 将显示以下窗口,让您选择想要运行 Android 应用程序的位置。

Let’s try to run your Android Testing application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.

choose device

选择您的移动设备作为选项,然后检查会显示应用程序屏幕的移动设备。现在,只需按照 Monkey 部分顶部的步骤操作,即可对该应用程序执行测试。

Select your mobile device as an option and then check your mobile device which will display application screen. Now just follow the steps mentioned at the top under the monkey section in order to perform testing on this application.