Getting Started with Testing ——開始單元測試

来源:http://www.cnblogs.com/taoyexian/archive/2016/07/18/5681392.html
-Advertisement-
Play Games

Android tests are based on JUnit, and you can run them either as local unit tests on the JVM or as instrumented tests on an Android device. This page ...


Android tests are based on JUnit, and you can run them either as local unit tests on the JVM or as instrumented tests on an Android device. This page provides an introduction to the concepts and tools for building Android tests.

// Android的測試基於JUnit

Test Types


When using Android Studio to write any of your tests, your test code must go into one of two different code directories (source sets). For each module in your project, Android Studio includes both source sets, corresponding to the following test types:

//對於每一個項目的模塊,Androidstudio都會包含這兩個類型的source sets

Local unit tests
Located at module-name/src/test/java/.

These tests run on the local JVM and do not have access to functional Android framework APIs.

// 這些測試運行在本地JAVA虛擬機上,不會訪問Android框架層的api

To get started, see Building Local Unit Tests.

Instrumented tests
Located at module-name/src/androidTest/java/.

These are all tests that must run on an Android hardware device or an Android emulator.

//這些測試必須運行在Android硬體設備上或者模擬器上

Instrumented tests are built into an APK that runs on the device alongside your app under test. The system runs your test APK and your app under tests in the same process, so your tests can invoke methods and modify fields in the app, and automate user interaction with your app.

//instruments test構建了一個apk和你的app一起安裝,系統會讓你的app和測試apk一同運行在同一個進程,這樣你的測試可以調用應用中的方法並且 可以修改變數,讓和應用的交互變得自動化

For information about how to create instrumented tests, see the following topics:

However, the local unit tests and instrumented tests described above are just terms that help distinguish the tests that run on your local JVM from the tests that run on the Android platform (on a hardware device or emulator). The real testing types that you should understand when building a complete test suite are described in the following table.

//然而上面描述的local unit test and instrumentes test只是幫助區分他們一個是運行在本地虛擬機,一個是運行在Android平臺上。真正的測試類型的分類應該是如下表描述的:

TypeSubtypeDescription
Unit tests
Local Unit Tests Unit tests that run locally on the Java Virtual Machine (JVM). Use these tests to minimize execution time when your tests have no Android framework dependencies or when you can mock the Android framework dependencies.
Instrumented unit tests Unit tests that run on an Android device or emulator. These tests have access to Instrumentationinformation, such as the Context of the app you are testing. Use these tests when your tests have Android dependencies that mock objects cannot satisfy.
Integration Tests
Components within your app only This type of test verifies that the target app behaves as expected when a user performs a specific action or enters a specific input in its activities. For example, it allows you to check that the target app returns the correct UI output in response to user interactions in the app’s activities. UI testing frameworks like Espressoallow you to programmatically simulate user actions and test complex intra-app user interactions.
Cross-app Components This type of test verifies the correct behavior of interactions between different user apps or between user apps and system apps. For example, you might want to test that your app behaves correctly when the user performs an action in the Android Settings menu. UI testing frameworks that support cross-app interactions, such as UI Automator, allow you to create tests for such scenarios.

Test APIs


The following are common APIs used for testing apps on Android.

JUnit

You should write your unit or integration test class as a JUnit 4 test class. The framework offers a convenient way to perform common setup, teardown, and assertion operations in your test.

A basic JUnit 4 test class is a Java class that contains one or more test methods. A test method begins with the @Test annotation and contains the code to exercise and verify a single functionality (that is, a logical unit) in the component that you want to test.

The following snippet shows an example JUnit 4 integration test that uses the Espresso APIs to perform a click action on a UI element, then checks to see if an expected string is displayed.

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityInstrumentationTest {

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

    @Test
    public void sayHello(){
        onView(withText("Say hello!")).perform(click());

        onView(withId(R.id.textView)).check(matches(withText("Hello, World!")));
    }
}

In your JUnit 4 test class, you can call out sections in your test code for special processing by using the following annotations:

//你可以通過下麵的註解喚起一些代碼段用戶特殊的處理

  • @Before: Use this annotation to specify a block of code that contains test setup operations. The test class invokes this code block before each test. You can have multiple @Before methods but the order in which the test class calls these methods is not guaranteed.                   // 用before註解來指定包含test代碼構建操作的代碼塊。測試類調用這個代碼塊在所有測試代碼之前,你可以有多個before聲明的代碼塊,但是他們的相對運行順序是沒法保證的
  • @After: This annotation specifies a block of code that contains test tear-down operations. The test class calls this code block after every test method. You can define multiple @After operations in your test code. Use this annotation to release any resources from memory          // after註解指定了包含有測試類的拆除工作的代碼塊。測試類調用這個代碼在所有測試方法之後,你可以定義多個after註解代碼塊。使用這個註解來釋放記憶體中的資源
  • @Test: Use this annotation to mark a test method. A single test class can contain multiple test methods, each prefixed with this annotation.    //使用test註解來標記測試方法,一個測試類可以包含多個測試方法,每一個方法都帶有test首碼
  • @Rule: Rules allow you to flexibly add or redefine the behavior of each test method in a reusable way. In Android testing, use this annotation together with one of the test rule classes that the Android Testing Support Library provides, such as ActivityTestRule or ServiceTestRule.   //rule允許你靈活添加和沖定義每一個測試方法的行為以便重用。在Android 測試中,會以它和其他的測試規則類一起使用,例如ActivityTestRule or ServiceTestRule
  • @BeforeClass: Use this annotation to specify static methods for each test class to invoke only once. This testing step is useful for expensive operations such as connecting to a database. //使用這個註解來指定一個對於每一個測試類只會調用一次的靜態方法,這個測試搭建方法對於開銷較大的操作例如連接資料庫等是非常有幫助的。
  • @AfterClass: Use this annotation to specify static methods for the test class to invoke only after all tests in the class have run. This testing step is useful for releasing any resources allocated in the @BeforeClass block.
  • @Test(timeout=): Some annotations support the ability to pass in elements for which you can set values. For example, you can specify a timeout period for the test. If the test starts but does not complete within the given timeout period, it automatically fails. You must specify the timeout period in milliseconds, for example: @Test(timeout=5000).   //一些註釋支持添加可以設置值的元素的功能,例如你可以指定一個超市時間對於這個測試。如果測試開始但是沒有在超時時間內完成,他會自動失敗,超時時間以毫秒指定

For more annotations, see the documentation for JUnit annotations and the Android annotations.

Use the JUnit Assert class to verify the correctness of an object's state. The assert methods compare values you expect from a test to the actual results and throw an exception if the comparison fails. Assertion classes describes these methods in more detail.

Android Testing Support Library

The Android Testing Support Library provides a set of APIs that allow you to quickly build and run test code for your apps, including JUnit 4 and functional UI tests. The library includes the following instrumentation-based APIs that are useful when you want to automate your tests:

AndroidJUnitRunnerA JUnit 4-compatible test runner for Android.EspressoA UI testing framework; suitable for functional UI testing within an app.UI AutomatorA UI testing framework suitable for cross-app functional UI testing between both system and installed apps.

Assertion classes

Because Android Testing Support Library APIs extend JUnit, you can use assertion methods to display the results of tests. An assertion method compares an actual value returned by a test to an expected value, and throws an AssertionException if the comparison test fails. Using assertions is more convenient than logging, and provides better test performance.

To simplify test development, you should use the Hamcrest library, which lets you create more flexible tests using the Hamcrest matcher APIs.

Monkey and monkeyrunner

The Android SDK includes two tools for functional-level app testing:

Monkey
This 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, and use it to stress-test your app, report back errors any that are encountered, or repeat a stream of events by running the tool multiple times with the same random number seed.
monkeyrunner
This tool is an API and execution environment for test programs written in Python. The API includes functions for connecting to a device, installing and uninstalling packages, taking screenshots, comparing two images, and running a test package against an app. Using the API, you can write a wide range of large, powerful, and complex tests. You run programs that use the API with the monkeyrunner command-line tool.

Guides for Building Android Tests


The following documents provide more detail about how to build and run a variety of test types:

Building Local Unit Tests
Build unit tests that have no dependencies or only simple dependencies that you can mock, which run on your local JVM.
Building Instrumented Unit Tests
Build complex unit tests with Android dependencies that cannot be satisfied with mock objects, which run on a hardware device or emulator.
Automating User Interface Tests
Create tests to verify that the user interface behaves correctly for user interactions within a single app or for interactions across multiple apps.
Testing App Compontent Integrations
Verify the behavior of components that users do not directly interact with, such as a service or a content provider.
Testing Display Performance
Write tests that measure your app's UI performance to ensure a consistently smooth user experience.
 
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本章內容: 定義 節點類型 節點關係 選擇器 樣式操作方法style 表格操作方法 表單操作方法 元素節點ELEMENT 屬性節點attributes 文本節點TEXT 文檔節點 Document 位置操作方法 定時器 彈出框 location 其它 事件操作 實例 定義 文檔對象模型(Docume ...
  • (幾個重點概念解析) 一、層疊上下文 二、層疊水平 三、層疊順序(以下層疊順序按照由內向外排列,即z軸上的值越來越大,越靠近用戶) 四、z-index 五、我的理解: 頁面中元素的層疊情況是由層疊順序這個規則決定的。在最初的頁面里,所有元素按照預設的情況依次排列。而z-index屬性像是一個外來戶, ...
  • $('div a'):div標簽下所有層次a元素的jquery對象 $('div>a'):div標簽下子元素層次a元素的jquery對象 ...
  • PlaceholderTextView 效果 源碼 https://github.com/YouXianMing/UI-Component-Collection 的 PlaceholderTextView ...
  • 剛剛請教了一個php高手。就hao123.com 來舉例。因為要考慮到一個公司的多個app。所以 如下樣式,如果公司名稱簡稱xtz,app的 名稱簡稱cht xtz.hao123.com xtzcht.hao123.com 如果是測試的話:test_xtzcht.hao123.com baiduap ...
  • Mac下載並編譯Google安卓AOSP項目代碼 參考 這兩天用Mac下載安卓AOSP源碼,且把遇到的問題記下來。當然作為一個菜鳥,難免會有錯誤或者描述不對的地方,歡迎各路大神小神批評指正。轉載請註明出處。 一、準備環境 (請提前安裝好xcode或command line tools) Instal ...
  • If your unit test has no dependencies or only has simple dependencies on Android, you should run your test on a local development machine. This testin ...
  • 廢話不多說,直接進入主題: 這裡要說的方式有6種:1、屬性傳值 2、block 3、delegate 4、UserDefault 5、單例 6、通知(篇幅原因我只寫核心代碼,如果看不懂可以直接在最下麵去github 看demo) 1、block(個人覺得最常用的場景下最好用的) 先說我最常用的blo ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...